test.cc 1022 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412
  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. // Small enough that the whole request is sent before the server turns it
  6849. // down, yet past the limit by the last chunks
  6850. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6851. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6852. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6853. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6854. SCOPED_TRACE(size_line.substr(0, 2));
  6855. std::string body;
  6856. for (auto c : std::string("dechunked post body")) {
  6857. body += size_line + "\r\n" + c + "\r\n";
  6858. }
  6859. body += "0\r\n\r\n";
  6860. expect_chunked_body_rejected(cli_, body.c_str());
  6861. }
  6862. }
  6863. TEST_F(ServerTest, AcceptsChunkExtension) {
  6864. expect_chunked_body_status(cli_,
  6865. "4;name=value\r\ndech\r\n"
  6866. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6867. "0;last\r\n\r\n",
  6868. StatusCode::OK_200);
  6869. }
  6870. TEST_F(ServerTest, GetStreamed2) {
  6871. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6874. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6875. EXPECT_EQ(true, res->has_header("Content-Range"));
  6876. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6877. EXPECT_EQ(std::string("ab"), res->body);
  6878. }
  6879. TEST_F(ServerTest, GetStreamed) {
  6880. auto res = cli_.Get("/streamed");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(std::string("aaabbb"), res->body);
  6885. }
  6886. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6887. auto res = cli_.Get("/streamed-without-length",
  6888. Headers{make_range_header({{0, -1}})});
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. EXPECT_EQ(false, res->has_header("Content-Length"));
  6892. EXPECT_EQ(false, res->has_header("Content-Range"));
  6893. EXPECT_EQ(std::string("abcdefg"), res->body);
  6894. }
  6895. TEST_F(ServerTest, GetStreamedWithRange1) {
  6896. auto res =
  6897. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6900. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6901. EXPECT_EQ(true, res->has_header("Content-Range"));
  6902. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6903. EXPECT_EQ(std::string("def"), res->body);
  6904. }
  6905. TEST_F(ServerTest, GetStreamedWithRange2) {
  6906. auto res =
  6907. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6910. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6911. EXPECT_EQ(true, res->has_header("Content-Range"));
  6912. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6913. EXPECT_EQ(std::string("bcdefg"), res->body);
  6914. }
  6915. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6916. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6919. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ(true, res->has_header("Content-Range"));
  6921. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6922. EXPECT_EQ(std::string("efg"), res->body);
  6923. }
  6924. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6925. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6926. // the entire representation.
  6927. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6928. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6931. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6932. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6933. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6934. }
  6935. }
  6936. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6937. auto res =
  6938. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6941. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6942. EXPECT_EQ(false, res->has_header("Content-Range"));
  6943. EXPECT_EQ(0U, res->body.size());
  6944. }
  6945. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6946. // Only a 206 is served as a partial representation. Under any other status
  6947. // `apply_ranges()` reported the full content length, so the body must match
  6948. // that header, and the content provider must never be asked for an offset
  6949. // outside the representation.
  6950. auto check = [&](int status, const char *range) {
  6951. auto path =
  6952. std::string("/streamed-with-range?status=") + std::to_string(status);
  6953. auto ctx = path + " Range: " + range;
  6954. auto res = cli_.Get(path, Headers{{"Range", range}});
  6955. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6956. EXPECT_EQ(status, res->status) << ctx;
  6957. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6959. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6960. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6961. };
  6962. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6963. check(403, "bytes=3-5");
  6964. // The offset is far past the representation.
  6965. check(403, "bytes=100000-100200");
  6966. // `first_pos` is still -1 here, and the bounds asserts in
  6967. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6968. check(403, "bytes=-3");
  6969. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6970. // multipart branch would have written one that is empty.
  6971. check(403, "bytes=1-2, 4-5");
  6972. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6973. // covers the whole representation.
  6974. check(200, "bytes=3-5");
  6975. check(200, "bytes=1-2, 4-5");
  6976. }
  6977. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6978. auto res =
  6979. cli_.Get("/streamed-with-range",
  6980. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6981. "92233720368547758079223372036854775807"}});
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6984. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6985. EXPECT_EQ(false, res->has_header("Content-Range"));
  6986. EXPECT_EQ(0U, res->body.size());
  6987. }
  6988. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6989. auto res = cli_.Get(
  6990. "/with-range",
  6991. Headers{{"Range",
  6992. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6993. {"Accept-Encoding", ""}});
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6996. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6997. EXPECT_EQ(true, res->has_header("Content-Range"));
  6998. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6999. EXPECT_EQ(std::string("abcdefg"), res->body);
  7000. }
  7001. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7002. auto res = cli_.Get("/with-range", Headers{
  7003. {"Range", "bytes=0-"},
  7004. {"Accept-Encoding", ""},
  7005. });
  7006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7007. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7008. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7009. EXPECT_EQ(true, res->has_header("Content-Range"));
  7010. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7011. EXPECT_EQ(std::string("abcdefg"), res->body);
  7012. }
  7013. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7014. auto res = cli_.Get("/streamed-with-range",
  7015. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(false, res->has_header("Content-Range"));
  7020. EXPECT_EQ(267U, res->body.size());
  7021. // Check that both range contents are present
  7022. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7023. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7024. // Check that Content-Range headers are present for both ranges
  7025. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7026. std::string::npos);
  7027. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7028. std::string::npos);
  7029. }
  7030. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7031. Ranges ranges;
  7032. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7033. ranges.emplace_back(0, -1);
  7034. }
  7035. auto res = cli_.Get("/streamed-with-range?error",
  7036. Headers{{make_range_header(ranges)}});
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7039. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7040. EXPECT_EQ(false, res->has_header("Content-Range"));
  7041. EXPECT_EQ(0U, res->body.size());
  7042. }
  7043. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7044. auto res = cli_.Get("/streamed-with-range",
  7045. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7048. EXPECT_EQ(5U, res->body.size());
  7049. // Check that overlapping ranges are coalesced into a single range
  7050. EXPECT_EQ("bcdef", res->body);
  7051. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7052. // Should be single range, not multipart
  7053. EXPECT_TRUE(res->has_header("Content-Range"));
  7054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(268U, res->body.size());
  7062. // Check that both range contents are present
  7063. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7064. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7065. // Check that Content-Range headers are present for both ranges
  7066. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7067. std::string::npos);
  7068. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7069. std::string::npos);
  7070. }
  7071. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7072. auto res = cli_.Get("/streamed-with-range",
  7073. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7076. EXPECT_EQ(269U, res->body.size());
  7077. // Check that both duplicate range contents are present
  7078. size_t first_abc = res->body.find("abc\r\n");
  7079. EXPECT_TRUE(first_abc != std::string::npos);
  7080. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7081. EXPECT_TRUE(second_abc != std::string::npos);
  7082. // Check that Content-Range headers are present for both ranges
  7083. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7084. EXPECT_TRUE(first_range != std::string::npos);
  7085. size_t second_range =
  7086. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7087. EXPECT_TRUE(second_range != std::string::npos);
  7088. }
  7089. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7090. auto res =
  7091. cli_.Get("/streamed-with-range?error",
  7092. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7095. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7096. EXPECT_EQ(false, res->has_header("Content-Range"));
  7097. EXPECT_EQ(0U, res->body.size());
  7098. }
  7099. TEST_F(ServerTest, GetStreamedEndless) {
  7100. uint64_t offset = 0;
  7101. auto res = cli_.Get("/streamed-cancel",
  7102. [&](const char * /*data*/, uint64_t data_length) {
  7103. if (offset < 100) {
  7104. offset += data_length;
  7105. return true;
  7106. }
  7107. return false;
  7108. });
  7109. ASSERT_TRUE(!res);
  7110. EXPECT_EQ(Error::Canceled, res.error());
  7111. }
  7112. TEST_F(ServerTest, ClientStop) {
  7113. std::atomic_size_t count{4};
  7114. std::vector<std::thread> threads;
  7115. for (auto i = count.load(); i != 0; --i) {
  7116. threads.emplace_back([&]() {
  7117. auto res = cli_.Get("/streamed-cancel",
  7118. [&](const char *, uint64_t) { return true; });
  7119. --count;
  7120. ASSERT_TRUE(!res);
  7121. EXPECT_TRUE(res.error() == Error::Canceled ||
  7122. res.error() == Error::Read || res.error() == Error::Write);
  7123. });
  7124. }
  7125. std::this_thread::sleep_for(std::chrono::seconds(2));
  7126. while (count != 0) {
  7127. cli_.stop();
  7128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7129. }
  7130. for (auto &t : threads) {
  7131. t.join();
  7132. }
  7133. }
  7134. TEST_F(ServerTest, GetWithRange1) {
  7135. auto res = cli_.Get("/with-range", Headers{
  7136. make_range_header({{3, 5}}),
  7137. {"Accept-Encoding", ""},
  7138. });
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7141. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7142. EXPECT_EQ(true, res->has_header("Content-Range"));
  7143. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7144. EXPECT_EQ(std::string("def"), res->body);
  7145. }
  7146. TEST_F(ServerTest, GetWithRange2) {
  7147. auto res = cli_.Get("/with-range", Headers{
  7148. make_range_header({{1, -1}}),
  7149. {"Accept-Encoding", ""},
  7150. });
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7153. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(true, res->has_header("Content-Range"));
  7155. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7156. EXPECT_EQ(std::string("bcdefg"), res->body);
  7157. }
  7158. TEST_F(ServerTest, GetWithRange3) {
  7159. auto res = cli_.Get("/with-range", Headers{
  7160. make_range_header({{0, 0}}),
  7161. {"Accept-Encoding", ""},
  7162. });
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7165. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7166. EXPECT_EQ(true, res->has_header("Content-Range"));
  7167. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7168. EXPECT_EQ(std::string("a"), res->body);
  7169. }
  7170. TEST_F(ServerTest, GetWithRange4) {
  7171. auto res = cli_.Get("/with-range", Headers{
  7172. make_range_header({{-1, 2}}),
  7173. {"Accept-Encoding", ""},
  7174. });
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7177. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7178. EXPECT_EQ(true, res->has_header("Content-Range"));
  7179. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7180. EXPECT_EQ(std::string("fg"), res->body);
  7181. }
  7182. TEST_F(ServerTest, GetWithRange5) {
  7183. auto res = cli_.Get("/with-range", Headers{
  7184. make_range_header({{0, 5}}),
  7185. {"Accept-Encoding", ""},
  7186. });
  7187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7189. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7190. EXPECT_EQ(true, res->has_header("Content-Range"));
  7191. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7192. EXPECT_EQ(std::string("abcdef"), res->body);
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7195. auto res =
  7196. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeMultipart) {
  7201. auto res =
  7202. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7205. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(267U, res->body.size());
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7210. auto res = cli_.Get("/with-range",
  7211. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7214. }
  7215. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7216. auto res = cli_.Get("/with-range-customized-response",
  7217. Headers{{make_range_header({{1, 2}})}});
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7220. EXPECT_EQ(true, res->has_header("Content-Length"));
  7221. EXPECT_EQ(false, res->has_header("Content-Range"));
  7222. EXPECT_EQ(JSON_DATA, res->body);
  7223. }
  7224. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7225. auto res = cli_.Get("/with-range-customized-response",
  7226. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7229. EXPECT_EQ(true, res->has_header("Content-Length"));
  7230. EXPECT_EQ(false, res->has_header("Content-Range"));
  7231. EXPECT_EQ(JSON_DATA, res->body);
  7232. }
  7233. TEST_F(ServerTest, Issue1772) {
  7234. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7237. }
  7238. TEST_F(ServerTest, Issue609) {
  7239. auto res = cli_.Delete("/issue609");
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::OK_200, res->status);
  7242. EXPECT_EQ(std::string("ok"), res->body);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedChunked) {
  7245. auto res = cli_.Get("/streamed-chunked");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. EXPECT_EQ(std::string("123456789"), res->body);
  7249. }
  7250. TEST_F(ServerTest, GetStreamedChunked2) {
  7251. auto res = cli_.Get("/streamed-chunked2");
  7252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. EXPECT_EQ(std::string("123456789"), res->body);
  7255. }
  7256. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7257. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ(std::string("123456789"), res->body);
  7261. EXPECT_TRUE(res->has_header("Trailer"));
  7262. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7263. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7264. // Trailers are now stored separately from headers (security fix)
  7265. EXPECT_EQ(2U, res->trailers.size());
  7266. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7267. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7268. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7269. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7270. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7271. // Verify trailers are NOT in headers (security verification)
  7272. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7273. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7274. }
  7275. TEST_F(ServerTest, LargeChunkedPost) {
  7276. Request req;
  7277. req.method = "POST";
  7278. req.path = "/large-chunked";
  7279. std::string host_and_port;
  7280. host_and_port += HOST;
  7281. host_and_port += ":";
  7282. host_and_port += std::to_string(PORT);
  7283. req.headers.emplace("Host", host_and_port.c_str());
  7284. req.headers.emplace("Accept", "*/*");
  7285. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7286. req.headers.emplace("Content-Type", "text/plain");
  7287. req.headers.emplace("Content-Length", "0");
  7288. req.headers.emplace("Transfer-Encoding", "chunked");
  7289. std::string long_string(30 * 1024u, 'a');
  7290. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7291. // Attempt to make a large enough post to exceed OS buffers, to test that
  7292. // the server handles short reads if the full chunk data isn't available.
  7293. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7294. auto res = std::make_shared<Response>();
  7295. auto error = Error::Success;
  7296. auto ret = cli_.send(req, *res, error);
  7297. ASSERT_TRUE(ret);
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. }
  7300. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7301. auto res = cli_.Get("/remote_addr");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7305. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7306. }
  7307. TEST_F(ServerTest, GetMethodLocalAddr) {
  7308. auto res = cli_.Get("/local_addr");
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7312. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7313. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7314. }
  7315. TEST_F(ServerTest, HTTPResponseSplitting) {
  7316. auto res = cli_.Get("/http_response_splitting");
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::OK_200, res->status);
  7319. }
  7320. TEST_F(ServerTest, SlowRequest) {
  7321. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7322. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7323. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7324. }
  7325. #if 0
  7326. TEST_F(ServerTest, SlowPost) {
  7327. char buffer[64 * 1024];
  7328. memset(buffer, 0x42, sizeof(buffer));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. auto ret = sink.write(buffer, sizeof(buffer));
  7333. EXPECT_TRUE(ret);
  7334. return true;
  7335. },
  7336. "text/plain");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST_F(ServerTest, SlowPostFail) {
  7341. char buffer[64 * 1024];
  7342. memset(buffer, 0x42, sizeof(buffer));
  7343. cli_.set_write_timeout(std::chrono::seconds(0));
  7344. auto res = cli_.Post(
  7345. "/slowpost", 64 * 1024 * 1024,
  7346. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7347. sink.write(buffer, sizeof(buffer));
  7348. return true;
  7349. },
  7350. "text/plain");
  7351. ASSERT_TRUE(!res);
  7352. EXPECT_EQ(Error::Write, res.error());
  7353. }
  7354. #endif
  7355. TEST_F(ServerTest, Put) {
  7356. auto res = cli_.Put("/put", "PUT", "text/plain");
  7357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7358. EXPECT_EQ(StatusCode::OK_200, res->status);
  7359. EXPECT_EQ("PUT", res->body);
  7360. }
  7361. TEST_F(ServerTest, PutWithContentProvider) {
  7362. auto res = cli_.Put(
  7363. "/put", 3,
  7364. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7365. sink.os << "PUT";
  7366. return true;
  7367. },
  7368. "text/plain");
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. EXPECT_EQ("PUT", res->body);
  7372. }
  7373. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7374. auto res = cli_.Post(
  7375. "/post", 42,
  7376. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7377. return false;
  7378. },
  7379. "text/plain");
  7380. ASSERT_TRUE(!res);
  7381. EXPECT_EQ(Error::Canceled, res.error());
  7382. }
  7383. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7384. auto res = cli_.Put(
  7385. "/put",
  7386. [](size_t /*offset*/, DataSink &sink) {
  7387. sink.os << "PUT";
  7388. sink.done();
  7389. return true;
  7390. },
  7391. "text/plain");
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::OK_200, res->status);
  7394. EXPECT_EQ("PUT", res->body);
  7395. }
  7396. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7397. auto res = cli_.Post(
  7398. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7399. "text/plain");
  7400. ASSERT_TRUE(!res);
  7401. EXPECT_EQ(Error::Canceled, res.error());
  7402. }
  7403. TEST_F(ServerTest, PostLoopBack) {
  7404. std::string body;
  7405. auto res = cli_.Post(
  7406. "/post-loopback", 9,
  7407. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7408. EXPECT_EQ(9u, length);
  7409. sink.write("123", 3);
  7410. sink.write("456", 3);
  7411. sink.write("789", 3);
  7412. return true;
  7413. },
  7414. "text/plain",
  7415. [&body](const char *data, size_t data_length) {
  7416. body.append(data, data_length);
  7417. return true;
  7418. });
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ("123456789", body);
  7422. }
  7423. TEST_F(ServerTest, PutLoopBack) {
  7424. std::string body;
  7425. auto res = cli_.Put(
  7426. "/put-loopback", 9,
  7427. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7428. EXPECT_EQ(9u, length);
  7429. sink.write("123", 3);
  7430. sink.write("456", 3);
  7431. sink.write("789", 3);
  7432. return true;
  7433. },
  7434. "text/plain",
  7435. [&body](const char *data, size_t data_length) {
  7436. body.append(data, data_length);
  7437. return true;
  7438. });
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("123456789", body);
  7442. }
  7443. TEST_F(ServerTest, PatchLoopBack) {
  7444. std::string body;
  7445. auto res = cli_.Patch(
  7446. "/patch-loopback", 9,
  7447. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7448. EXPECT_EQ(9u, length);
  7449. sink.write("123", 3);
  7450. sink.write("456", 3);
  7451. sink.write("789", 3);
  7452. return true;
  7453. },
  7454. "text/plain",
  7455. [&body](const char *data, size_t data_length) {
  7456. body.append(data, data_length);
  7457. return true;
  7458. });
  7459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. EXPECT_EQ("123456789", body);
  7462. }
  7463. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7464. std::string body;
  7465. auto res = cli_.Post(
  7466. "/post-loopback",
  7467. [](size_t /*offset*/, DataSink &sink) {
  7468. sink.write("123", 3);
  7469. sink.write("456", 3);
  7470. sink.write("789", 3);
  7471. sink.done();
  7472. return true;
  7473. },
  7474. "text/plain",
  7475. [&body](const char *data, size_t data_length) {
  7476. body.append(data, data_length);
  7477. return true;
  7478. });
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. EXPECT_EQ("123456789", body);
  7482. }
  7483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7484. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7485. cli_.set_compress(true);
  7486. auto res = cli_.Put(
  7487. "/put", 3,
  7488. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7489. sink.os << "PUT";
  7490. return true;
  7491. },
  7492. "text/plain");
  7493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. EXPECT_EQ("PUT", res->body);
  7496. }
  7497. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7498. cli_.set_compress(true);
  7499. auto res = cli_.Post(
  7500. "/post", 42,
  7501. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7502. return false;
  7503. },
  7504. "text/plain");
  7505. ASSERT_TRUE(!res);
  7506. EXPECT_EQ(Error::Canceled, res.error());
  7507. }
  7508. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7509. cli_.set_compress(true);
  7510. auto res = cli_.Put(
  7511. "/put",
  7512. [](size_t /*offset*/, DataSink &sink) {
  7513. sink.os << "PUT";
  7514. sink.done();
  7515. return true;
  7516. },
  7517. "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("PUT", res->body);
  7521. }
  7522. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7523. cli_.set_compress(true);
  7524. auto res = cli_.Post(
  7525. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7526. "text/plain");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::Canceled, res.error());
  7529. }
  7530. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(LARGE_DATA, res->body);
  7536. }
  7537. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7538. #ifdef CPPHTTPLIB_SSL_ENABLED
  7539. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7540. Client cli(s.c_str());
  7541. cli.enable_server_certificate_verification(false);
  7542. #else
  7543. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7544. Client cli(s.c_str());
  7545. #endif
  7546. cli.set_compress(true);
  7547. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. EXPECT_EQ(LARGE_DATA, res->body);
  7551. // The compressed size should be less than a 10th of the original. May vary
  7552. // depending on the zlib library.
  7553. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7554. static_cast<uint64_t>(10 * 1024 * 1024));
  7555. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7556. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7557. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7558. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7559. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7560. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7561. #endif
  7562. }
  7563. TEST_F(ServerTest, PutContentWithDeflate) {
  7564. cli_.set_compress(false);
  7565. Headers headers;
  7566. headers.emplace("Content-Encoding", "deflate");
  7567. // PUT in deflate format:
  7568. auto res = cli_.Put("/put", headers,
  7569. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ("PUT", res->body);
  7573. }
  7574. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7575. Headers headers;
  7576. headers.emplace("Accept-Encoding", "gzip, deflate");
  7577. auto res = cli_.Get("/streamed-chunked", headers);
  7578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7579. EXPECT_EQ(StatusCode::OK_200, res->status);
  7580. EXPECT_EQ(std::string("123456789"), res->body);
  7581. }
  7582. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7583. Headers headers;
  7584. headers.emplace("Accept-Encoding", "gzip, deflate");
  7585. auto res = cli_.Get("/streamed-chunked2", headers);
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. EXPECT_EQ(std::string("123456789"), res->body);
  7589. }
  7590. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7591. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. }
  7595. TEST(GzipDecompressor, ChunkedDecompression) {
  7596. std::string data;
  7597. for (size_t i = 0; i < 32 * 1024; ++i) {
  7598. data.push_back(static_cast<char>('a' + i % 26));
  7599. }
  7600. std::string compressed_data;
  7601. {
  7602. httplib::detail::gzip_compressor compressor;
  7603. bool result = compressor.compress(
  7604. data.data(), data.size(),
  7605. /*last=*/true,
  7606. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7607. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7608. compressed_data_size);
  7609. return true;
  7610. });
  7611. ASSERT_TRUE(result);
  7612. }
  7613. std::string decompressed_data;
  7614. {
  7615. httplib::detail::gzip_decompressor decompressor;
  7616. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7617. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7618. size_t chunk_size = 130;
  7619. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7620. chunk_begin += chunk_size) {
  7621. size_t current_chunk_size =
  7622. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7623. bool result = decompressor.decompress(
  7624. compressed_data.data() + chunk_begin, current_chunk_size,
  7625. [&](const char *decompressed_data_chunk,
  7626. size_t decompressed_data_chunk_size) {
  7627. decompressed_data.insert(decompressed_data.size(),
  7628. decompressed_data_chunk,
  7629. decompressed_data_chunk_size);
  7630. return true;
  7631. });
  7632. ASSERT_TRUE(result);
  7633. }
  7634. }
  7635. ASSERT_EQ(data, decompressed_data);
  7636. }
  7637. TEST(GzipDecompressor, DeflateDecompression) {
  7638. std::string original_text = "Raw deflate without gzip";
  7639. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7640. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7641. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7642. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7643. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7644. std::string decompressed_data;
  7645. {
  7646. httplib::detail::gzip_decompressor decompressor;
  7647. bool result = decompressor.decompress(
  7648. compressed_data.data(), compressed_data.size(),
  7649. [&](const char *decompressed_data_chunk,
  7650. size_t decompressed_data_chunk_size) {
  7651. decompressed_data.insert(decompressed_data.size(),
  7652. decompressed_data_chunk,
  7653. decompressed_data_chunk_size);
  7654. return true;
  7655. });
  7656. ASSERT_TRUE(result);
  7657. }
  7658. ASSERT_EQ(original_text, decompressed_data);
  7659. }
  7660. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7661. std::string original_text = "Raw deflate without gzip";
  7662. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7663. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7664. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7665. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7666. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7668. std::string decompressed_data;
  7669. {
  7670. httplib::detail::gzip_decompressor decompressor;
  7671. bool result = decompressor.decompress(
  7672. compressed_data.data(), compressed_data.size(),
  7673. [&](const char *decompressed_data_chunk,
  7674. size_t decompressed_data_chunk_size) {
  7675. decompressed_data.insert(decompressed_data.size(),
  7676. decompressed_data_chunk,
  7677. decompressed_data_chunk_size);
  7678. return true;
  7679. });
  7680. ASSERT_TRUE(result);
  7681. }
  7682. ASSERT_EQ(original_text, decompressed_data);
  7683. }
  7684. #endif
  7685. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7686. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7687. Headers headers;
  7688. headers.emplace("Accept-Encoding", "br");
  7689. auto res = cli_.Get("/streamed-chunked", headers);
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::OK_200, res->status);
  7692. EXPECT_EQ(std::string("123456789"), res->body);
  7693. }
  7694. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7695. Headers headers;
  7696. headers.emplace("Accept-Encoding", "br");
  7697. auto res = cli_.Get("/streamed-chunked2", headers);
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ(std::string("123456789"), res->body);
  7701. }
  7702. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7703. cli_.set_compress(true);
  7704. auto res = cli_.Put(
  7705. "/put", 3,
  7706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7707. sink.os << "PUT";
  7708. return true;
  7709. },
  7710. "text/plain");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. EXPECT_EQ("PUT", res->body);
  7714. }
  7715. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7716. cli_.set_compress(true);
  7717. auto res = cli_.Put(
  7718. "/put",
  7719. [](size_t /*offset*/, DataSink &sink) {
  7720. sink.os << "PUT";
  7721. sink.done();
  7722. return true;
  7723. },
  7724. "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7730. cli_.set_compress(true);
  7731. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. EXPECT_EQ(LARGE_DATA, res->body);
  7735. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7736. }
  7737. #endif
  7738. TEST_F(ServerTest, Patch) {
  7739. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("PATCH", res->body);
  7743. }
  7744. TEST_F(ServerTest, Delete) {
  7745. auto res = cli_.Delete("/delete");
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ("DELETE", res->body);
  7749. }
  7750. TEST_F(ServerTest, DeleteContentReceiver) {
  7751. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ("content", res->body);
  7755. }
  7756. TEST_F(ServerTest, Options) {
  7757. auto res = cli_.Options("*");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7761. EXPECT_TRUE(res->body.empty());
  7762. }
  7763. TEST_F(ServerTest, URL) {
  7764. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, ArrayParam) {
  7769. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. }
  7773. TEST_F(ServerTest, ArrayParamValues) {
  7774. auto res =
  7775. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. }
  7779. TEST_F(ServerTest, NoMultipleHeaders) {
  7780. Headers headers = {{"Content-Length", "5"}};
  7781. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7782. "text/plain");
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. }
  7786. TEST_F(ServerTest, PostContentReceiver) {
  7787. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. ASSERT_EQ(StatusCode::OK_200, res->status);
  7790. ASSERT_EQ("content", res->body);
  7791. }
  7792. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7793. UploadFormDataItems items = {
  7794. {"text1", "text default", "", ""},
  7795. {"text2", "aωb", "", ""},
  7796. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7797. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7798. {"file3", "", "", "application/octet-stream"},
  7799. };
  7800. auto res = cli_.Post("/content_receiver", items);
  7801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7802. EXPECT_EQ(StatusCode::OK_200, res->status);
  7803. }
  7804. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7805. UploadFormDataItems items = {
  7806. {"text1", "text default", "", ""},
  7807. {"text2", "aωb", "", ""},
  7808. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7809. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7810. {"file3", "", "", "application/octet-stream"},
  7811. };
  7812. auto boundary = std::string("+++++");
  7813. std::string body;
  7814. for (const auto &item : items) {
  7815. body += "--" + boundary + "\r\n";
  7816. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7817. if (!item.filename.empty()) {
  7818. body += "; filename=\"" + item.filename + "\"";
  7819. }
  7820. body += "\r\n";
  7821. if (!item.content_type.empty()) {
  7822. body += "Content-Type: " + item.content_type + "\r\n";
  7823. }
  7824. body += "\r\n";
  7825. body += item.content + "\r\n";
  7826. }
  7827. body += "--" + boundary + "--\r\n";
  7828. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7829. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7831. EXPECT_EQ(StatusCode::OK_200, res->status);
  7832. }
  7833. TEST(MultipartFormDataTest, FieldEscaping) {
  7834. Server svr;
  7835. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7836. const ContentReader &content_reader) {
  7837. ASSERT_TRUE(req.is_multipart_form_data());
  7838. std::vector<FormData> received;
  7839. content_reader(
  7840. [&](const FormData &file) {
  7841. received.push_back(file);
  7842. return true;
  7843. },
  7844. [&](const char *data, size_t data_length) {
  7845. received.back().content.append(data, data_length);
  7846. return true;
  7847. });
  7848. // '"', CR and LF in names and filenames are escaped following the
  7849. // WHATWG HTML standard, so each part still parses as a single part
  7850. // with no injected headers. Content types get CR/LF escaped too,
  7851. // while '"' (legal there, e.g. quoted charset) is preserved.
  7852. ASSERT_EQ(4U, received.size());
  7853. EXPECT_EQ("na%22me", received[0].name);
  7854. EXPECT_EQ("quoted name", received[0].content);
  7855. EXPECT_EQ("file", received[1].name);
  7856. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7857. received[1].filename);
  7858. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7859. EXPECT_EQ("injected", received[1].content);
  7860. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7861. EXPECT_EQ("my%22file.txt", received[2].filename);
  7862. EXPECT_EQ("cr lf name", received[2].content);
  7863. EXPECT_EQ("typed", received[3].name);
  7864. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7865. received[3].content_type);
  7866. EXPECT_EQ("typed content", received[3].content);
  7867. });
  7868. auto port = svr.bind_to_any_port("localhost");
  7869. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7870. auto se = detail::scope_exit([&] {
  7871. svr.stop();
  7872. t.join();
  7873. ASSERT_FALSE(svr.is_running());
  7874. });
  7875. svr.wait_until_ready();
  7876. Client cli("localhost", port);
  7877. UploadFormDataItems items = {
  7878. {"na\"me", "quoted name", "", ""},
  7879. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7880. "application/octet-stream"},
  7881. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7882. {"typed", "typed content", "",
  7883. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7884. };
  7885. auto res = cli.Post("/post", items);
  7886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7890. const UploadFormDataItems items = {
  7891. {"name1", "Content 1", "", ""},
  7892. {"name2", "Content 2", "file2.txt", "text/plain"},
  7893. };
  7894. Server svr;
  7895. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7896. const ContentReader &content_reader) {
  7897. ASSERT_TRUE(req.is_multipart_form_data());
  7898. std::vector<FormData> received;
  7899. content_reader(
  7900. [&](const FormData &file) {
  7901. received.push_back(file);
  7902. return true;
  7903. },
  7904. [&](const char *data, size_t data_length) {
  7905. received.back().content.append(data, data_length);
  7906. return true;
  7907. });
  7908. ASSERT_EQ(2U, received.size());
  7909. EXPECT_EQ("name1", received[0].name);
  7910. EXPECT_EQ("Content 1", received[0].content);
  7911. EXPECT_EQ("name2", received[1].name);
  7912. EXPECT_EQ("Content 2", received[1].content);
  7913. EXPECT_EQ("file2.txt", received[1].filename);
  7914. EXPECT_EQ("text/plain", received[1].content_type);
  7915. });
  7916. auto port = svr.bind_to_any_port("localhost");
  7917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7918. auto se = detail::scope_exit([&] {
  7919. svr.stop();
  7920. t.join();
  7921. ASSERT_FALSE(svr.is_running());
  7922. });
  7923. svr.wait_until_ready();
  7924. Client cli("localhost", port);
  7925. // Whole-body serialization with a generated boundary
  7926. {
  7927. MultipartFormDataWriter writer;
  7928. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7929. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7930. writer.content_type());
  7931. auto body = writer.serialize(items);
  7932. EXPECT_EQ(body.size(), writer.content_length(items));
  7933. auto res = cli.Post("/post", body, writer.content_type());
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. }
  7937. // Per-part framing with a custom boundary via a content provider
  7938. {
  7939. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7940. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7941. MultipartFormDataWriter writer("custom-boundary_123");
  7942. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7943. std::string body;
  7944. for (const auto &item : items) {
  7945. body += writer.item_begin(item);
  7946. body += item.content;
  7947. body += MultipartFormDataWriter::item_end();
  7948. }
  7949. body += writer.finish();
  7950. EXPECT_EQ(body.size(), writer.content_length(items));
  7951. auto res = cli.Post(
  7952. "/post", body.size(),
  7953. [&](size_t offset, size_t length, DataSink &sink) {
  7954. sink.write(body.data() + offset, length);
  7955. return true;
  7956. },
  7957. writer.content_type());
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. }
  7961. }
  7962. TEST_F(ServerTest, PostContentReceiverGzip) {
  7963. cli_.set_compress(true);
  7964. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7966. ASSERT_EQ(StatusCode::OK_200, res->status);
  7967. ASSERT_EQ("content", res->body);
  7968. }
  7969. TEST_F(ServerTest, PutContentReceiver) {
  7970. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7972. ASSERT_EQ(StatusCode::OK_200, res->status);
  7973. ASSERT_EQ("content", res->body);
  7974. }
  7975. TEST_F(ServerTest, PatchContentReceiver) {
  7976. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. ASSERT_EQ(StatusCode::OK_200, res->status);
  7979. ASSERT_EQ("content", res->body);
  7980. }
  7981. template <typename ClientType>
  7982. void TestWithHeadersAndContentReceiver(
  7983. ClientType &cli,
  7984. std::function<Result(ClientType &, const std::string &, const Headers &,
  7985. const std::string &, const std::string &,
  7986. ContentReceiver, DownloadProgress)>
  7987. request_func) {
  7988. Headers headers;
  7989. headers.emplace("X-Custom-Header", "test-value");
  7990. std::string received_body;
  7991. auto res = request_func(
  7992. cli, "/content_receiver", headers, "content", "application/json",
  7993. [&](const char *data, size_t data_length) {
  7994. received_body.append(data, data_length);
  7995. return true;
  7996. },
  7997. nullptr);
  7998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7999. EXPECT_EQ(StatusCode::OK_200, res->status);
  8000. EXPECT_EQ("content", received_body);
  8001. }
  8002. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8003. #ifdef CPPHTTPLIB_SSL_ENABLED
  8004. using ClientT = SSLClient;
  8005. #else
  8006. using ClientT = Client;
  8007. #endif
  8008. TestWithHeadersAndContentReceiver<ClientT>(
  8009. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8010. const std::string &body, const std::string &content_type,
  8011. ContentReceiver receiver, DownloadProgress progress) {
  8012. return cli.Post(path, headers, body, content_type, receiver, progress);
  8013. });
  8014. }
  8015. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8016. #ifdef CPPHTTPLIB_SSL_ENABLED
  8017. using ClientT = SSLClient;
  8018. #else
  8019. using ClientT = Client;
  8020. #endif
  8021. TestWithHeadersAndContentReceiver<ClientT>(
  8022. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8023. const std::string &body, const std::string &content_type,
  8024. ContentReceiver receiver, DownloadProgress progress) {
  8025. return cli.Put(path, headers, body, content_type, receiver, progress);
  8026. });
  8027. }
  8028. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8029. #ifdef CPPHTTPLIB_SSL_ENABLED
  8030. using ClientT = SSLClient;
  8031. #else
  8032. using ClientT = Client;
  8033. #endif
  8034. TestWithHeadersAndContentReceiver<ClientT>(
  8035. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8036. const std::string &body, const std::string &content_type,
  8037. ContentReceiver receiver, DownloadProgress progress) {
  8038. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8039. });
  8040. }
  8041. template <typename ClientType>
  8042. void TestWithHeadersAndContentReceiverWithProgress(
  8043. ClientType &cli,
  8044. std::function<Result(ClientType &, const std::string &, const Headers &,
  8045. const std::string &, const std::string &,
  8046. ContentReceiver, DownloadProgress)>
  8047. request_func) {
  8048. Headers headers;
  8049. headers.emplace("X-Test-Header", "progress-test");
  8050. std::string received_body;
  8051. auto progress_called = false;
  8052. auto res = request_func(
  8053. cli, "/content_receiver", headers, "content", "text/plain",
  8054. [&](const char *data, size_t data_length) {
  8055. received_body.append(data, data_length);
  8056. return true;
  8057. },
  8058. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8059. progress_called = true;
  8060. return true;
  8061. });
  8062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8063. EXPECT_EQ(StatusCode::OK_200, res->status);
  8064. EXPECT_EQ("content", received_body);
  8065. EXPECT_TRUE(progress_called);
  8066. }
  8067. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8068. #ifdef CPPHTTPLIB_SSL_ENABLED
  8069. using ClientT = SSLClient;
  8070. #else
  8071. using ClientT = Client;
  8072. #endif
  8073. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8074. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8075. const std::string &body, const std::string &content_type,
  8076. ContentReceiver receiver, DownloadProgress progress) {
  8077. return cli.Post(path, headers, body, content_type, receiver, progress);
  8078. });
  8079. }
  8080. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8081. #ifdef CPPHTTPLIB_SSL_ENABLED
  8082. using ClientT = SSLClient;
  8083. #else
  8084. using ClientT = Client;
  8085. #endif
  8086. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8087. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8088. const std::string &body, const std::string &content_type,
  8089. ContentReceiver receiver, DownloadProgress progress) {
  8090. return cli.Put(path, headers, body, content_type, receiver, progress);
  8091. });
  8092. }
  8093. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8094. #ifdef CPPHTTPLIB_SSL_ENABLED
  8095. using ClientT = SSLClient;
  8096. #else
  8097. using ClientT = Client;
  8098. #endif
  8099. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8100. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8101. const std::string &body, const std::string &content_type,
  8102. ContentReceiver receiver, DownloadProgress progress) {
  8103. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8104. });
  8105. }
  8106. template <typename ClientType>
  8107. void TestWithHeadersAndContentReceiverError(
  8108. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8109. const Headers &, const std::string &,
  8110. const std::string &, ContentReceiver)>
  8111. request_func) {
  8112. Headers headers;
  8113. headers.emplace("X-Error-Test", "true");
  8114. std::string received_body;
  8115. auto receiver_failed = false;
  8116. auto res =
  8117. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8118. [&](const char *data, size_t data_length) {
  8119. received_body.append(data, data_length);
  8120. receiver_failed = true;
  8121. return false;
  8122. });
  8123. ASSERT_FALSE(res);
  8124. EXPECT_TRUE(receiver_failed);
  8125. }
  8126. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8127. #ifdef CPPHTTPLIB_SSL_ENABLED
  8128. using ClientT = SSLClient;
  8129. #else
  8130. using ClientT = Client;
  8131. #endif
  8132. TestWithHeadersAndContentReceiverError<ClientT>(
  8133. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8134. const std::string &body, const std::string &content_type,
  8135. ContentReceiver receiver) {
  8136. return cli.Post(path, headers, body, content_type, receiver);
  8137. });
  8138. }
  8139. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8140. #ifdef CPPHTTPLIB_SSL_ENABLED
  8141. using ClientT = SSLClient;
  8142. #else
  8143. using ClientT = Client;
  8144. #endif
  8145. TestWithHeadersAndContentReceiverError<ClientT>(
  8146. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8147. const std::string &body, const std::string &content_type,
  8148. ContentReceiver receiver) {
  8149. return cli.Put(path, headers, body, content_type, receiver);
  8150. });
  8151. }
  8152. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8153. #ifdef CPPHTTPLIB_SSL_ENABLED
  8154. using ClientT = SSLClient;
  8155. #else
  8156. using ClientT = Client;
  8157. #endif
  8158. TestWithHeadersAndContentReceiverError<ClientT>(
  8159. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8160. const std::string &body, const std::string &content_type,
  8161. ContentReceiver receiver) {
  8162. return cli.Patch(path, headers, body, content_type, receiver);
  8163. });
  8164. }
  8165. TEST_F(ServerTest, PostQueryStringAndBody) {
  8166. auto res =
  8167. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. ASSERT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST_F(ServerTest, HTTP2Magic) {
  8172. Request req;
  8173. req.method = "PRI";
  8174. req.path = "*";
  8175. req.body = "SM";
  8176. auto res = std::make_shared<Response>();
  8177. auto error = Error::Success;
  8178. auto ret = cli_.send(req, *res, error);
  8179. ASSERT_TRUE(ret);
  8180. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8181. }
  8182. TEST_F(ServerTest, KeepAlive) {
  8183. auto res = cli_.Get("/hi");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8187. EXPECT_EQ("Hello World!", res->body);
  8188. res = cli_.Get("/hi");
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8192. EXPECT_EQ("Hello World!", res->body);
  8193. res = cli_.Get("/hi");
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::OK_200, res->status);
  8196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("Hello World!", res->body);
  8198. res = cli_.Get("/not-exist");
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8201. res = cli_.Post("/empty", "", "text/plain");
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. EXPECT_EQ(StatusCode::OK_200, res->status);
  8204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8205. EXPECT_EQ("empty", res->body);
  8206. EXPECT_EQ("close", res->get_header_value("Connection"));
  8207. res = cli_.Post(
  8208. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8209. "text/plain");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8213. EXPECT_EQ("empty", res->body);
  8214. cli_.set_keep_alive(false);
  8215. res = cli_.Get("/last-request");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("close", res->get_header_value("Connection"));
  8219. }
  8220. TEST_F(ServerTest, TooManyRedirect) {
  8221. cli_.set_follow_location(true);
  8222. auto res = cli_.Get("/redirect/0");
  8223. ASSERT_TRUE(!res);
  8224. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8225. }
  8226. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8227. Request req;
  8228. req.method = "FOOBAR";
  8229. req.path = "/hi";
  8230. cli_.set_keep_alive(true);
  8231. auto res = cli_.send(req);
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8234. EXPECT_EQ("close", res->get_header_value("Connection"));
  8235. EXPECT_FALSE(cli_.is_socket_open());
  8236. }
  8237. TEST_F(ServerTest, CustomRouteReadsBody) {
  8238. const std::string xml =
  8239. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8240. Request req;
  8241. req.method = "PROPFIND";
  8242. req.path = "/dav/dir";
  8243. req.set_header("Depth", "1");
  8244. req.body = xml;
  8245. auto res = cli_.send(req);
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8248. EXPECT_EQ(xml, res->body);
  8249. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8250. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8251. }
  8252. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8253. Request req;
  8254. req.method = "PROPFIND";
  8255. req.path = "/dav/42";
  8256. auto res = cli_.send(req);
  8257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8258. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8259. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8260. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8261. }
  8262. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8263. Request req;
  8264. req.method = "PROPFIND";
  8265. req.path = "/dav-re/123";
  8266. auto res = cli_.send(req);
  8267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8268. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8269. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8270. }
  8271. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8272. Request req;
  8273. req.method = "MKCOL";
  8274. req.path = "/dav-mkcol";
  8275. auto res = cli_.send(req);
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::Created_201, res->status);
  8278. }
  8279. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8280. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8281. Request req;
  8282. req.method = "REPORT";
  8283. req.path = "/dav-report";
  8284. req.body = xml;
  8285. auto res = cli_.send(req);
  8286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8287. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8288. EXPECT_EQ(xml, res->body);
  8289. }
  8290. // A content reader route must fire even when the request carries no body,
  8291. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8292. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8293. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8294. Request req;
  8295. req.method = "REPORT";
  8296. req.path = "/dav-report";
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8300. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8301. }
  8302. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8303. Request req;
  8304. req.method = "PROPFIND";
  8305. req.path = "/not-dav";
  8306. auto res = cli_.send(req);
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8309. }
  8310. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8311. Request req;
  8312. req.method = "UNLOCK";
  8313. req.path = "/dav/dir";
  8314. cli_.set_keep_alive(true);
  8315. auto res = cli_.send(req);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8318. EXPECT_EQ("close", res->get_header_value("Connection"));
  8319. EXPECT_FALSE(cli_.is_socket_open());
  8320. }
  8321. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8322. // The mount point serves this path, but only for GET and HEAD.
  8323. auto get_res = cli_.Get("/dir/index.html");
  8324. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8325. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8326. Request req;
  8327. req.method = "PROPFIND";
  8328. req.path = "/dir/index.html";
  8329. auto res = cli_.send(req);
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8332. }
  8333. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8334. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8335. cli_.set_keep_alive(true);
  8336. for (auto i = 0; i < 2; i++) {
  8337. Request req;
  8338. req.method = "PROPFIND";
  8339. req.path = "/dav/dir";
  8340. req.body = xml;
  8341. auto res = cli_.send(req);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8344. EXPECT_EQ(xml, res->body);
  8345. EXPECT_TRUE(cli_.is_socket_open());
  8346. }
  8347. // A built-in method must still be served on the same connection.
  8348. cli_.set_keep_alive(false);
  8349. auto res = cli_.Get("/hi");
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_EQ("close", res->get_header_value("Connection"));
  8353. }
  8354. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8355. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8356. Request req;
  8357. req.method = "PROPFIND";
  8358. req.path = "/dav/dir";
  8359. req.set_header("Expect", "100-continue");
  8360. req.body = xml;
  8361. auto res = cli_.send(req);
  8362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8364. EXPECT_EQ(xml, res->body);
  8365. }
  8366. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8367. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8368. TEST_F(ServerTest, Gzip) {
  8369. Headers headers;
  8370. headers.emplace("Accept-Encoding", "gzip, deflate");
  8371. auto res = cli_.Get("/compress", headers);
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8374. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8375. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8376. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8377. "7890123456789012345678901234567890",
  8378. res->body);
  8379. EXPECT_EQ(StatusCode::OK_200, res->status);
  8380. }
  8381. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8382. Headers headers;
  8383. headers.emplace("Accept-Encoding", "gzip, deflate");
  8384. auto res = cli_.Get("/compress-with-charset", headers);
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8387. EXPECT_EQ("application/json; charset=utf-8",
  8388. res->get_header_value("Content-Type"));
  8389. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8390. "7890123456789012345678901234567890",
  8391. res->body);
  8392. EXPECT_EQ(StatusCode::OK_200, res->status);
  8393. }
  8394. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8395. Headers headers;
  8396. headers.emplace("Accept-Encoding", "");
  8397. auto res = cli_.Get("/compress", headers);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8400. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8401. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8402. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8403. "7890123456789012345678901234567890",
  8404. res->body);
  8405. EXPECT_EQ(StatusCode::OK_200, res->status);
  8406. }
  8407. TEST_F(ServerTest, GzipWithContentReceiver) {
  8408. Headers headers;
  8409. headers.emplace("Accept-Encoding", "gzip, deflate");
  8410. std::string body;
  8411. auto res =
  8412. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8413. EXPECT_EQ(100U, data_length);
  8414. body.append(data, data_length);
  8415. return true;
  8416. });
  8417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8418. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8420. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8421. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8422. "7890123456789012345678901234567890",
  8423. body);
  8424. EXPECT_EQ(StatusCode::OK_200, res->status);
  8425. }
  8426. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8427. Headers headers;
  8428. headers.emplace("Accept-Encoding", "gzip, deflate");
  8429. cli_.set_decompress(false);
  8430. auto res = cli_.Get("/compress", headers);
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8434. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8435. EXPECT_EQ(33U, res->body.size());
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8439. Headers headers;
  8440. headers.emplace("Accept-Encoding", "");
  8441. std::string body;
  8442. auto res =
  8443. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8444. EXPECT_EQ(100U, data_length);
  8445. body.append(data, data_length);
  8446. return true;
  8447. });
  8448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8449. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8451. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8452. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8453. "7890123456789012345678901234567890",
  8454. body);
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, NoGzip) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "gzip, deflate");
  8460. auto res = cli_.Get("/nocompress", headers);
  8461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8462. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8463. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8464. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8465. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8466. "7890123456789012345678901234567890",
  8467. res->body);
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. }
  8470. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8471. Headers headers;
  8472. headers.emplace("Accept-Encoding", "gzip, deflate");
  8473. std::string body;
  8474. auto res = cli_.Get("/nocompress", headers,
  8475. [&](const char *data, size_t data_length) {
  8476. EXPECT_EQ(100U, data_length);
  8477. body.append(data, data_length);
  8478. return true;
  8479. });
  8480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8481. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8482. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8483. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8484. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8485. "7890123456789012345678901234567890",
  8486. body);
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. }
  8489. TEST_F(ServerTest, MultipartFormDataGzip) {
  8490. UploadFormDataItems items = {
  8491. {"key1", "test", "", ""},
  8492. {"key2", "--abcdefg123", "", ""},
  8493. };
  8494. cli_.set_compress(true);
  8495. auto res = cli_.Post("/compress-multipart", items);
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. }
  8499. #endif
  8500. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8501. // Static file compression is opt-in, so these run their own server rather than
  8502. // flipping it on for the shared ServerTest fixture, which would silently
  8503. // rewrite what every other static file test is asserting.
  8504. class StaticFileCompressionTest : public ::testing::Test {
  8505. protected:
  8506. void TearDown() override {
  8507. if (t_.joinable()) {
  8508. svr_.stop();
  8509. t_.join();
  8510. }
  8511. }
  8512. int start(const std::function<void(Server &)> &configure = nullptr) {
  8513. // Serves the same tree as a directory of build-time compressed assets
  8514. // would be served: the mount point names the coding the files are already
  8515. // stored in. Registered before "/" so it is the one that matches.
  8516. svr_.set_mount_point("/pre-encoded", "./www",
  8517. {{"Content-Encoding", "gzip"}});
  8518. svr_.set_mount_point("/", "./www");
  8519. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8520. res.set_file_content("./www/dir/index.html", "text/html");
  8521. });
  8522. svr_.Get("/pre-encoded-file-content",
  8523. [](const Request & /*req*/, Response &res) {
  8524. res.set_header("Content-Encoding", "gzip");
  8525. res.set_file_content("./www/dir/index.html", "text/html");
  8526. });
  8527. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8528. res.set_content_provider(
  8529. 6, "text/plain",
  8530. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8531. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8532. return true;
  8533. });
  8534. });
  8535. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8536. res.set_content_provider(
  8537. 1000, "text/plain",
  8538. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8539. if (offset < 100) {
  8540. std::string data(100, 'A');
  8541. sink.write(data.data(), data.size());
  8542. return true;
  8543. }
  8544. std::this_thread::sleep_for(std::chrono::seconds(2));
  8545. std::string data(900, 'B');
  8546. sink.write(data.data(), data.size());
  8547. return true;
  8548. });
  8549. });
  8550. if (configure) { configure(svr_); }
  8551. auto port = svr_.bind_to_any_port(HOST);
  8552. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8553. svr_.wait_until_ready();
  8554. return port;
  8555. }
  8556. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8557. // Every file under ./www except 1MB.txt is smaller than the default
  8558. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8559. // it out of the way.
  8560. static void enable_without_floor(Server &svr) {
  8561. svr.set_static_file_compression(true);
  8562. svr.set_static_file_compression_min_length(0);
  8563. }
  8564. Server svr_;
  8565. std::thread t_;
  8566. };
  8567. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8568. auto port = start();
  8569. Client cli(HOST, port);
  8570. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. EXPECT_EQ(StatusCode::OK_200, res->status);
  8573. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8574. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8575. EXPECT_EQ(1048576U, res->body.size());
  8576. }
  8577. TEST_F(StaticFileCompressionTest, MountPoint) {
  8578. auto port = start(enable);
  8579. Client cli(HOST, port);
  8580. cli.set_decompress(false);
  8581. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8583. EXPECT_EQ(StatusCode::OK_200, res->status);
  8584. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8587. // The response stays self-delimiting: a length, not a chunked body.
  8588. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8589. EXPECT_EQ(std::to_string(res->body.size()),
  8590. res->get_header_value("Content-Length"));
  8591. EXPECT_LT(res->body.size(), 1048576U);
  8592. EXPECT_FALSE(res->body.empty());
  8593. }
  8594. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8595. auto port = start(enable);
  8596. Client cli(HOST, port);
  8597. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8599. EXPECT_EQ(StatusCode::OK_200, res->status);
  8600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8601. EXPECT_EQ(1048576U, res->body.size());
  8602. }
  8603. TEST_F(StaticFileCompressionTest, FileContent) {
  8604. auto port = start(enable_without_floor);
  8605. Client cli(HOST, port);
  8606. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::OK_200, res->status);
  8609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8610. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8611. EXPECT_EQ(104U, res->body.size());
  8612. }
  8613. // A handler that serves an already-encoded file names the coding itself. The
  8614. // file-backed path decided its coding from Accept-Encoding and the content
  8615. // type alone, so it compressed the stored bytes a second time and appended a
  8616. // second Content-Encoding field line.
  8617. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8618. auto port = start(enable_without_floor);
  8619. Client cli(HOST, port);
  8620. cli.set_decompress(false);
  8621. auto res = cli.Get("/pre-encoded-file-content",
  8622. Headers{{"Accept-Encoding", "gzip"}});
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8626. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8627. // Vary belongs to a coding the server chose, and it chose none here.
  8628. EXPECT_FALSE(res->has_header("Vary"));
  8629. // The file travels exactly as it is stored on disk.
  8630. EXPECT_EQ(104U, res->body.size());
  8631. }
  8632. // The 1MB file clears the default floor, so this one runs the configuration a
  8633. // deployment would actually have.
  8634. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8635. auto port = start(enable);
  8636. Client cli(HOST, port);
  8637. cli.set_decompress(false);
  8638. auto res =
  8639. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8643. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8644. EXPECT_FALSE(res->has_header("Vary"));
  8645. EXPECT_EQ(1048576U, res->body.size());
  8646. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8647. }
  8648. TEST_F(StaticFileCompressionTest, Head) {
  8649. auto port = start(enable);
  8650. Client cli(HOST, port);
  8651. cli.set_decompress(false);
  8652. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8653. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8654. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8658. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8659. // HEAD still reports the size a GET would return.
  8660. EXPECT_EQ(get->get_header_value("Content-Length"),
  8661. res->get_header_value("Content-Length"));
  8662. EXPECT_TRUE(res->body.empty());
  8663. }
  8664. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8665. auto port = start(enable);
  8666. Client cli(HOST, port);
  8667. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8668. {"Accept-Encoding", "gzip"}});
  8669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8670. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8671. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8672. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8673. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8674. EXPECT_EQ("cd", res->body);
  8675. }
  8676. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8677. auto port = start(enable);
  8678. Client cli(HOST, port);
  8679. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8683. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8684. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8685. }
  8686. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8687. auto port = start(enable);
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8693. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8694. EXPECT_TRUE(res->body.empty());
  8695. }
  8696. TEST_F(StaticFileCompressionTest, MinLength) {
  8697. auto port = start(enable);
  8698. Client cli(HOST, port);
  8699. // 104 bytes, well under the default floor. Compressing it would add the
  8700. // gzip header and trailer to a body that already fits in one packet.
  8701. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ(StatusCode::OK_200, res->status);
  8704. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8705. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(1);
  8711. });
  8712. Client cli(HOST, port);
  8713. cli.set_decompress(false);
  8714. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8717. // A 9-byte file comes back larger than it went in, because gzip's header and
  8718. // trailer outweigh anything deflate can save. That is the end of the range
  8719. // the floor exists to keep out.
  8720. EXPECT_GT(res->body.size(), 9U);
  8721. }
  8722. TEST_F(StaticFileCompressionTest, MaxLength) {
  8723. auto port = start([](Server &svr) {
  8724. svr.set_static_file_compression(true);
  8725. svr.set_static_file_compression_min_length(0);
  8726. svr.set_static_file_compression_max_length(1024);
  8727. });
  8728. Client cli(HOST, port);
  8729. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8730. // defines `small` as a macro on Windows.
  8731. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8732. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8733. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8734. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8735. // Under it: compressed.
  8736. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8738. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8739. }
  8740. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8741. auto port = start(enable_without_floor);
  8742. Client cli(HOST, port);
  8743. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8744. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8745. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8746. auto identity_etag = identity->get_header_value("ETag");
  8747. ASSERT_FALSE(identity_etag.empty());
  8748. auto gzipped =
  8749. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8750. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8751. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8752. auto gzip_etag = gzipped->get_header_value("ETag");
  8753. ASSERT_FALSE(gzip_etag.empty());
  8754. // Two representations, two validators.
  8755. EXPECT_NE(identity_etag, gzip_etag);
  8756. // Each one revalidates against the request that would produce it...
  8757. auto fresh =
  8758. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8759. {"If-None-Match", gzip_etag}});
  8760. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8761. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8762. auto fresh_identity =
  8763. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8764. {"If-None-Match", identity_etag}});
  8765. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8766. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8767. // ...and not against the other representation.
  8768. auto crossed =
  8769. cli.Get("/dir/index.html",
  8770. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8771. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8772. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8773. }
  8774. // The opt-in covers responses the server reads off disk itself. A caller's own
  8775. // known-length provider keeps its Content-Length and, more importantly, keeps
  8776. // delivering incrementally: routing it through a compressor would hold every
  8777. // write back until zlib's window filled.
  8778. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8779. auto port = start(enable);
  8780. Client cli(HOST, port);
  8781. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8783. EXPECT_EQ(StatusCode::OK_200, res->status);
  8784. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8785. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8786. EXPECT_EQ("aaabbb", res->body);
  8787. }
  8788. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8789. auto port = start(enable);
  8790. Client cli(HOST, port);
  8791. cli.set_read_timeout(1, 0);
  8792. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8793. Headers{{"Accept-Encoding", "gzip"}});
  8794. ASSERT_TRUE(handle.is_valid());
  8795. // The provider writes 100 bytes and then stalls for longer than the read
  8796. // timeout. Those first bytes have to arrive anyway: run the response through
  8797. // a compressor and zlib holds them until its window fills, so the read would
  8798. // come back empty instead.
  8799. char buf[256];
  8800. auto n = handle.read(buf, sizeof(buf));
  8801. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8802. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8806. TEST_F(ServerTest, Brotli) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "br");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. #endif
  8820. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8821. TEST_F(ServerTest, Zstd) {
  8822. Headers headers;
  8823. headers.emplace("Accept-Encoding", "zstd");
  8824. auto res = cli_.Get("/compress", headers);
  8825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8826. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8828. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8829. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8830. "7890123456789012345678901234567890",
  8831. res->body);
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. }
  8834. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8835. Headers headers;
  8836. headers.emplace("Accept-Encoding", "");
  8837. auto res = cli_.Get("/compress", headers);
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8841. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8842. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8843. "7890123456789012345678901234567890",
  8844. res->body);
  8845. EXPECT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8848. Headers headers;
  8849. headers.emplace("Accept-Encoding", "zstd");
  8850. std::string body;
  8851. auto res =
  8852. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8853. EXPECT_EQ(100U, data_length);
  8854. body.append(data, data_length);
  8855. return true;
  8856. });
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8860. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8862. "7890123456789012345678901234567890",
  8863. body);
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. }
  8866. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8867. Headers headers;
  8868. headers.emplace("Accept-Encoding", "zstd");
  8869. cli_.set_decompress(false);
  8870. auto res = cli_.Get("/compress", headers);
  8871. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8872. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8873. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8874. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8878. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8879. EXPECT_EQ(StatusCode::OK_200, res->status);
  8880. ASSERT_EQ(26U, res->body.size());
  8881. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8882. 0);
  8883. }
  8884. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8885. Headers headers;
  8886. headers.emplace("Accept-Encoding", "");
  8887. std::string body;
  8888. auto res =
  8889. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8890. EXPECT_EQ(100U, data_length);
  8891. body.append(data, data_length);
  8892. return true;
  8893. });
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8897. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8899. "7890123456789012345678901234567890",
  8900. body);
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. }
  8903. TEST_F(ServerTest, NoZstd) {
  8904. Headers headers;
  8905. headers.emplace("Accept-Encoding", "zstd");
  8906. auto res = cli_.Get("/nocompress", headers);
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8909. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8912. "7890123456789012345678901234567890",
  8913. res->body);
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8917. Headers headers;
  8918. headers.emplace("Accept-Encoding", "zstd");
  8919. std::string body;
  8920. auto res = cli_.Get("/nocompress", headers,
  8921. [&](const char *data, size_t data_length) {
  8922. EXPECT_EQ(100U, data_length);
  8923. body.append(data, data_length);
  8924. return true;
  8925. });
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8928. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8929. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8931. "7890123456789012345678901234567890",
  8932. body);
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. }
  8935. // TODO: How to enable zstd ??
  8936. TEST_F(ServerTest, MultipartFormDataZstd) {
  8937. UploadFormDataItems items = {
  8938. {"key1", "test", "", ""},
  8939. {"key2", "--abcdefg123", "", ""},
  8940. };
  8941. Headers headers;
  8942. headers.emplace("Accept-Encoding", "zstd");
  8943. cli_.set_compress(true);
  8944. auto res = cli_.Post("/compress-multipart", headers, items);
  8945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8946. EXPECT_EQ(StatusCode::OK_200, res->status);
  8947. }
  8948. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8949. Headers headers;
  8950. headers.emplace("Accept-Encoding", "zstd");
  8951. cli_.set_compress(true);
  8952. auto res = cli_.Put(
  8953. "/put", headers, 3,
  8954. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8955. sink.os << "PUT";
  8956. return true;
  8957. },
  8958. "text/plain");
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. EXPECT_EQ("PUT", res->body);
  8962. }
  8963. // Pre-compression logging tests
  8964. TEST_F(ServerTest, PreCompressionLogging) {
  8965. // Test data for compression (matches the actual /compress endpoint content)
  8966. const std::string test_content =
  8967. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8968. "3456789012345678901234567890";
  8969. // Variables to capture logging data
  8970. std::string pre_compression_body;
  8971. std::string pre_compression_content_type;
  8972. std::string pre_compression_content_encoding;
  8973. std::string post_compression_body;
  8974. std::string post_compression_content_type;
  8975. std::string post_compression_content_encoding;
  8976. // Set up pre-compression logger
  8977. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8978. const Response &res) {
  8979. pre_compression_body = res.body;
  8980. pre_compression_content_type = res.get_header_value("Content-Type");
  8981. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8982. });
  8983. // Set up post-compression logger
  8984. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8985. post_compression_body = res.body;
  8986. post_compression_content_type = res.get_header_value("Content-Type");
  8987. post_compression_content_encoding =
  8988. res.get_header_value("Content-Encoding");
  8989. });
  8990. // Test with gzip compression
  8991. Headers headers;
  8992. headers.emplace("Accept-Encoding", "gzip");
  8993. auto res = cli_.Get("/compress", headers);
  8994. // Verify response was compressed
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8998. // Verify pre-compression logger captured uncompressed content
  8999. EXPECT_EQ(test_content, pre_compression_body);
  9000. EXPECT_EQ("text/plain", pre_compression_content_type);
  9001. EXPECT_TRUE(pre_compression_content_encoding
  9002. .empty()); // No encoding header before compression
  9003. // Verify post-compression logger captured compressed content
  9004. EXPECT_NE(test_content,
  9005. post_compression_body); // Should be different after compression
  9006. EXPECT_EQ("text/plain", post_compression_content_type);
  9007. EXPECT_EQ("gzip", post_compression_content_encoding);
  9008. // Verify compressed content is smaller
  9009. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9010. }
  9011. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9012. const std::string test_content =
  9013. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9014. "3456789012345678901234567890";
  9015. std::string pre_compression_body;
  9016. std::string post_compression_body;
  9017. svr_.set_pre_compression_logger(
  9018. [&](const Request & /*req*/, const Response &res) {
  9019. pre_compression_body = res.body;
  9020. });
  9021. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9022. post_compression_body = res.body;
  9023. });
  9024. Headers headers;
  9025. headers.emplace("Accept-Encoding", "br");
  9026. auto res = cli_.Get("/compress", headers);
  9027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9028. EXPECT_EQ(StatusCode::OK_200, res->status);
  9029. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9030. // Verify pre-compression content is uncompressed
  9031. EXPECT_EQ(test_content, pre_compression_body);
  9032. // Verify post-compression content is compressed
  9033. EXPECT_NE(test_content, post_compression_body);
  9034. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9035. }
  9036. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9037. const std::string test_content =
  9038. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9039. "3456789012345678901234567890";
  9040. std::string pre_compression_body;
  9041. std::string post_compression_body;
  9042. svr_.set_pre_compression_logger(
  9043. [&](const Request & /*req*/, const Response &res) {
  9044. pre_compression_body = res.body;
  9045. });
  9046. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9047. post_compression_body = res.body;
  9048. });
  9049. // Request without compression (use /nocompress endpoint)
  9050. Headers headers;
  9051. auto res = cli_.Get("/nocompress", headers);
  9052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9053. EXPECT_EQ(StatusCode::OK_200, res->status);
  9054. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9055. // Pre-compression logger should not be called when no compression is applied
  9056. EXPECT_TRUE(
  9057. pre_compression_body.empty()); // Pre-compression logger not called
  9058. EXPECT_EQ(
  9059. test_content,
  9060. post_compression_body); // Post-compression logger captures final content
  9061. }
  9062. TEST_F(ServerTest, LoggerSeesContentLength) {
  9063. size_t logged_content_length = 0;
  9064. std::string logged_content_length_header;
  9065. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9066. logged_content_length = res.content_length_;
  9067. logged_content_length_header = res.get_header_value("Content-Length");
  9068. });
  9069. auto res = cli_.Get("/nocompress");
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. EXPECT_EQ(res->body.size(), logged_content_length);
  9073. EXPECT_EQ(std::to_string(logged_content_length),
  9074. logged_content_length_header);
  9075. }
  9076. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9077. const std::string test_content =
  9078. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9079. "3456789012345678901234567890";
  9080. std::string pre_compression_body;
  9081. bool pre_logger_called = false;
  9082. // Set only pre-compression logger
  9083. svr_.set_pre_compression_logger(
  9084. [&](const Request & /*req*/, const Response &res) {
  9085. pre_compression_body = res.body;
  9086. pre_logger_called = true;
  9087. });
  9088. Headers headers;
  9089. headers.emplace("Accept-Encoding", "gzip");
  9090. auto res = cli_.Get("/compress", headers);
  9091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9092. EXPECT_EQ(StatusCode::OK_200, res->status);
  9093. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9094. // Verify pre-compression logger was called
  9095. EXPECT_TRUE(pre_logger_called);
  9096. EXPECT_EQ(test_content, pre_compression_body);
  9097. }
  9098. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9099. {
  9100. // Test with Expect: 100-continue header - success case
  9101. // Server returns 100 Continue, client sends body, server returns 200 OK
  9102. Request req;
  9103. req.method = "POST";
  9104. req.path = "/post-large";
  9105. req.set_header("Expect", "100-continue");
  9106. req.body = LARGE_DATA;
  9107. Response res;
  9108. auto error = Error::Success;
  9109. cli_.set_keep_alive(true);
  9110. auto ret = cli_.send(req, res, error);
  9111. EXPECT_TRUE(ret);
  9112. EXPECT_EQ(StatusCode::OK_200, res.status);
  9113. EXPECT_EQ(LARGE_DATA, res.body);
  9114. }
  9115. {
  9116. // Test with Expect: 100-continue header - error case
  9117. // Client should not send the body when server returns an error
  9118. Request req;
  9119. req.method = "POST";
  9120. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9121. req.set_header("Expect", "100-continue");
  9122. req.body = LARGE_DATA;
  9123. Response res;
  9124. auto error = Error::Success;
  9125. auto start = std::chrono::high_resolution_clock::now();
  9126. cli_.set_keep_alive(true);
  9127. auto ret = cli_.send(req, res, error);
  9128. auto end = std::chrono::high_resolution_clock::now();
  9129. auto elapsed =
  9130. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9131. .count();
  9132. // With Expect: 100-continue, request completes successfully but with error
  9133. EXPECT_TRUE(ret);
  9134. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9135. EXPECT_EQ("close", res.get_header_value("Connection"));
  9136. EXPECT_FALSE(cli_.is_socket_open());
  9137. EXPECT_LE(elapsed, 2000);
  9138. }
  9139. {
  9140. // Send an extra GET request to ensure error recovery without hanging
  9141. Request req;
  9142. req.method = "GET";
  9143. req.path = "/hi";
  9144. auto start = std::chrono::high_resolution_clock::now();
  9145. auto res = cli_.send(req);
  9146. auto end = std::chrono::high_resolution_clock::now();
  9147. auto elapsed =
  9148. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9149. .count();
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ("Hello World!", res->body);
  9153. EXPECT_LE(elapsed, 500);
  9154. }
  9155. }
  9156. TEST(ZstdDecompressor, ChunkedDecompression) {
  9157. std::string data;
  9158. for (size_t i = 0; i < 32 * 1024; ++i) {
  9159. data.push_back(static_cast<char>('a' + i % 26));
  9160. }
  9161. std::string compressed_data;
  9162. {
  9163. httplib::detail::zstd_compressor compressor;
  9164. bool result = compressor.compress(
  9165. data.data(), data.size(),
  9166. /*last=*/true,
  9167. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9168. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9169. compressed_data_size);
  9170. return true;
  9171. });
  9172. ASSERT_TRUE(result);
  9173. }
  9174. std::string decompressed_data;
  9175. {
  9176. httplib::detail::zstd_decompressor decompressor;
  9177. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9178. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9179. size_t chunk_size = 130;
  9180. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9181. chunk_begin += chunk_size) {
  9182. size_t current_chunk_size =
  9183. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9184. bool result = decompressor.decompress(
  9185. compressed_data.data() + chunk_begin, current_chunk_size,
  9186. [&](const char *decompressed_data_chunk,
  9187. size_t decompressed_data_chunk_size) {
  9188. decompressed_data.insert(decompressed_data.size(),
  9189. decompressed_data_chunk,
  9190. decompressed_data_chunk_size);
  9191. return true;
  9192. });
  9193. ASSERT_TRUE(result);
  9194. }
  9195. }
  9196. ASSERT_EQ(data, decompressed_data);
  9197. }
  9198. TEST(ZstdDecompressor, Decompress) {
  9199. std::string original_text = "Compressed with ZSTD";
  9200. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9201. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9202. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9203. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9204. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9205. std::string decompressed_data;
  9206. {
  9207. httplib::detail::zstd_decompressor decompressor;
  9208. bool result = decompressor.decompress(
  9209. compressed_data.data(), compressed_data.size(),
  9210. [&](const char *decompressed_data_chunk,
  9211. size_t decompressed_data_chunk_size) {
  9212. decompressed_data.insert(decompressed_data.size(),
  9213. decompressed_data_chunk,
  9214. decompressed_data_chunk_size);
  9215. return true;
  9216. });
  9217. ASSERT_TRUE(result);
  9218. }
  9219. ASSERT_EQ(original_text, decompressed_data);
  9220. }
  9221. #endif
  9222. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9223. // separate chunks so that the server sees each part in its own read(). Used to
  9224. // place a read boundary at a specific offset of a request body.
  9225. static bool send_request_in_parts(time_t read_timeout_sec,
  9226. const std::vector<std::string> &parts,
  9227. std::string *resp = nullptr,
  9228. int port = PORT) {
  9229. auto error = Error::Success;
  9230. auto client_sock = detail::create_client_socket(
  9231. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9232. /*connection_timeout_sec=*/5, 0,
  9233. /*read_timeout_sec=*/5, 0,
  9234. /*write_timeout_sec=*/5, 0, std::string(), error);
  9235. if (client_sock == INVALID_SOCKET) { return false; }
  9236. auto ret = detail::process_client_socket(
  9237. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9238. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9239. for (size_t i = 0; i < parts.size(); i++) {
  9240. const auto &part = parts[i];
  9241. if (part.size() !=
  9242. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9243. return false;
  9244. }
  9245. if (i + 1 < parts.size()) {
  9246. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9247. }
  9248. }
  9249. char buf[512];
  9250. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9251. while (line_reader.getline()) {
  9252. if (resp) { *resp += line_reader.ptr(); }
  9253. }
  9254. return true;
  9255. });
  9256. detail::close_socket(client_sock);
  9257. return ret;
  9258. }
  9259. // Sends a raw request to a server listening at HOST:PORT.
  9260. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9261. std::string *resp = nullptr, int port = PORT) {
  9262. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9263. }
  9264. #ifdef CPPHTTPLIB_SSL_ENABLED
  9265. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9267. ASSERT_TRUE(svr.is_valid());
  9268. svr.set_read_timeout(1, 0);
  9269. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9270. auto se = detail::scope_exit([&] {
  9271. svr.stop();
  9272. t.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. });
  9275. svr.wait_until_ready();
  9276. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9277. // keeps each wait well within the read timeout. The server gives up a
  9278. // second in, so the bytes sent after that fail.
  9279. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9280. parts.resize(26, std::string(1, '\0'));
  9281. EXPECT_FALSE(send_request_in_parts(5, parts));
  9282. }
  9283. #endif
  9284. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9285. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9286. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9287. const std::vector<std::string> &parts,
  9288. std::string *resp = nullptr,
  9289. int port = PORT) {
  9290. auto error = Error::Success;
  9291. auto sock = detail::create_client_socket(
  9292. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9293. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9294. /*write_timeout_sec=*/5, 0, std::string(), error);
  9295. if (sock == INVALID_SOCKET) { return false; }
  9296. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9297. auto ctx = SSL_CTX_new(TLS_client_method());
  9298. auto ssl = SSL_new(ctx);
  9299. auto ssl_se = detail::scope_exit([&] {
  9300. SSL_free(ssl);
  9301. SSL_CTX_free(ctx);
  9302. });
  9303. SSL_set_fd(ssl, static_cast<int>(sock));
  9304. if (SSL_connect(ssl) != 1) { return false; }
  9305. for (size_t i = 0; i < parts.size(); i++) {
  9306. const auto &part = parts[i];
  9307. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9308. static_cast<int>(part.size())) {
  9309. return false;
  9310. }
  9311. if (i + 1 < parts.size()) {
  9312. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9313. }
  9314. }
  9315. char buf[512];
  9316. int n;
  9317. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9318. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9319. }
  9320. return true;
  9321. }
  9322. #endif
  9323. // The request line, then a header value a byte at a time.
  9324. static std::vector<std::string> slow_request_head_parts() {
  9325. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9326. parts.resize(26, "a");
  9327. parts.emplace_back("\r\n\r\n");
  9328. return parts;
  9329. }
  9330. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9331. // within the one-second read timeout. The server gives up a second in, before
  9332. // the head is complete.
  9333. static void
  9334. expect_slow_request_head_dropped(Server &svr,
  9335. const std::function<std::string()> &send) {
  9336. std::atomic<bool> handled(false);
  9337. svr.Get("/", [&](const Request &, Response &res) {
  9338. handled = true;
  9339. res.set_content("ok", "text/plain");
  9340. });
  9341. svr.set_read_timeout(1, 0);
  9342. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9343. auto se = detail::scope_exit([&] {
  9344. svr.stop();
  9345. t.join();
  9346. ASSERT_FALSE(svr.is_running());
  9347. });
  9348. svr.wait_until_ready();
  9349. auto resp = send();
  9350. EXPECT_FALSE(handled);
  9351. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9352. }
  9353. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9354. Server svr;
  9355. expect_slow_request_head_dropped(svr, [] {
  9356. std::string resp;
  9357. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9358. return resp;
  9359. });
  9360. }
  9361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9362. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9364. ASSERT_TRUE(svr.is_valid());
  9365. expect_slow_request_head_dropped(svr, [] {
  9366. std::string resp;
  9367. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9368. return resp;
  9369. });
  9370. }
  9371. #endif
  9372. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9373. Server svr;
  9374. std::string header_value;
  9375. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9376. header_value = req.get_header_value("foo");
  9377. res.set_content("ok", "text/plain");
  9378. });
  9379. thread t = thread([&] { svr.listen(HOST, PORT); });
  9380. auto se = detail::scope_exit([&] {
  9381. svr.stop();
  9382. t.join();
  9383. ASSERT_FALSE(svr.is_running());
  9384. });
  9385. svr.wait_until_ready();
  9386. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9387. // like characters are not treated the same - use vertical tab and escape.
  9388. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9389. "foo: \t \v bar \x1B\t \r\n"
  9390. "Connection: close\r\n"
  9391. "\r\n";
  9392. std::string res;
  9393. ASSERT_TRUE(send_request(5, req, &res));
  9394. EXPECT_EQ(header_value, "");
  9395. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9396. }
  9397. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9398. Server svr;
  9399. std::string received;
  9400. svr.Get("/order", [&](const Request &req, Response &res) {
  9401. received = entries_to_string(req.headers);
  9402. res.set_content("ok", "text/plain");
  9403. });
  9404. auto port = svr.bind_to_any_port(HOST);
  9405. thread t = thread([&] { svr.listen_after_bind(); });
  9406. auto se = detail::scope_exit([&] {
  9407. svr.stop();
  9408. t.join();
  9409. ASSERT_FALSE(svr.is_running());
  9410. });
  9411. svr.wait_until_ready();
  9412. const std::string req = "GET /order HTTP/1.1\r\n"
  9413. "Host: localhost\r\n"
  9414. "X-First: 1\r\n"
  9415. "X-Dup: a\r\n"
  9416. "X-Second: 2\r\n"
  9417. "X-Dup: b\r\n"
  9418. "Connection: close\r\n"
  9419. "\r\n";
  9420. std::string res;
  9421. ASSERT_TRUE(send_request(5, req, &res, port));
  9422. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9423. EXPECT_EQ(
  9424. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9425. received);
  9426. }
  9427. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9428. Server svr;
  9429. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9430. res.set_header("Set-Cookie", "first=1");
  9431. res.set_header("X-Between", "y");
  9432. res.set_header("Set-Cookie", "second=2");
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. auto port = svr.bind_to_any_port(HOST);
  9436. thread t = thread([&] { svr.listen_after_bind(); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. t.join();
  9440. ASSERT_FALSE(svr.is_running());
  9441. });
  9442. svr.wait_until_ready();
  9443. Client cli(HOST, port);
  9444. auto res = cli.Get("/cookies");
  9445. ASSERT_TRUE(res);
  9446. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9447. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9448. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9449. }
  9450. // A stream may send a byte at a time with a small extension on each chunk,
  9451. // however long it runs
  9452. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9453. Server svr;
  9454. svr.Post("/count", [](const Request &req, Response &res) {
  9455. res.set_content(std::to_string(req.body.size()), "text/plain");
  9456. });
  9457. auto port = svr.bind_to_any_port(HOST);
  9458. ASSERT_LT(0, port);
  9459. thread t = thread([&] { svr.listen_after_bind(); });
  9460. auto se = detail::scope_exit([&] {
  9461. svr.stop();
  9462. t.join();
  9463. ASSERT_FALSE(svr.is_running());
  9464. });
  9465. svr.wait_until_ready();
  9466. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9467. "\r\nTransfer-Encoding: chunked\r\n"
  9468. "Connection: close\r\n\r\n";
  9469. for (auto i = 0; i < 4096; i++) {
  9470. req += "1;a=b\r\nx\r\n";
  9471. }
  9472. req += "0\r\n\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res, port));
  9475. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9476. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9477. }
  9478. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9479. Server svr;
  9480. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9481. auto i = new int(0);
  9482. res.set_header("Trailer", "X-Safe, X-Reflected");
  9483. res.set_chunked_content_provider(
  9484. "text/plain",
  9485. [i](size_t /*offset*/, DataSink &sink) {
  9486. if (*i == 0) {
  9487. sink.os << "body";
  9488. } else {
  9489. Headers trailer;
  9490. // A valid trailer that must survive.
  9491. trailer.emplace("X-Safe", "safe");
  9492. // Attacker-controlled value carrying CR/LF (response splitting).
  9493. trailer.emplace("X-Reflected",
  9494. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9495. // Attacker-controlled name carrying CR/LF.
  9496. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9497. sink.done_with_trailer(trailer);
  9498. }
  9499. (*i)++;
  9500. return true;
  9501. },
  9502. [i](bool /*success*/) { delete i; });
  9503. });
  9504. thread t = thread([&] { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. ASSERT_FALSE(svr.is_running());
  9509. });
  9510. svr.wait_until_ready();
  9511. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9512. "Host: " + HOST +
  9513. "\r\n"
  9514. "Connection: close\r\n"
  9515. "\r\n";
  9516. std::string res;
  9517. ASSERT_TRUE(send_request(5, req, &res));
  9518. // The injected fields must not appear anywhere in the raw response.
  9519. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9520. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9521. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9522. // Invalid trailers are dropped entirely, matching set_header().
  9523. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9524. // The valid trailer still passes through.
  9525. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9526. }
  9527. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9528. // A custom header writer gets only the fields the default one writes
  9529. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9530. std::string s;
  9531. for (const auto &h : hdrs) {
  9532. s += h.first + ": " + h.second + "\r\n";
  9533. }
  9534. s += "\r\n";
  9535. return strm.write(s.data(), s.size());
  9536. };
  9537. for (auto custom_writer : {false, true}) {
  9538. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9539. Server svr;
  9540. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9541. svr.set_post_routing_handler([](const Request &, Response &res) {
  9542. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9543. });
  9544. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9545. // res.headers is a public field an application can populate directly,
  9546. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9547. // A valid header that must survive.
  9548. res.headers.emplace("X-Safe", "safe");
  9549. // Attacker-controlled value carrying CR/LF (response splitting).
  9550. res.headers.emplace("X-Reflected",
  9551. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9552. // Attacker-controlled name carrying CR/LF.
  9553. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9554. res.set_content("body", "text/plain");
  9555. });
  9556. thread t = thread([&] { svr.listen(HOST, PORT); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. t.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.wait_until_ready();
  9563. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9564. "Host: " + HOST +
  9565. "\r\n"
  9566. "Connection: close\r\n"
  9567. "\r\n";
  9568. std::string res;
  9569. ASSERT_TRUE(send_request(5, req, &res));
  9570. // The injected fields must not appear anywhere in the raw response.
  9571. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9572. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9573. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9574. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9575. // Invalid headers are dropped entirely, matching set_header().
  9576. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9577. // The valid header still passes through.
  9578. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9579. }
  9580. }
  9581. // Forward declaration: in split builds split.py strips `inline` and moves the
  9582. // definition into httplib.cc, so detail::write_request_line is not visible from
  9583. // the public httplib.h. Re-declaring it here lets the tests link against the
  9584. // symbol in both header-only and split builds.
  9585. namespace httplib {
  9586. namespace detail {
  9587. ssize_t write_request_line(Stream &strm, const std::string &method,
  9588. const std::string &path);
  9589. } // namespace detail
  9590. } // namespace httplib
  9591. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9592. // A well-formed target is written verbatim.
  9593. {
  9594. detail::BufferStream strm;
  9595. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9596. EXPECT_GT(n, 0);
  9597. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9598. }
  9599. // A target carrying CR/LF, SP or other control octets must be rejected
  9600. // before anything reaches the wire, otherwise it splits the request line and
  9601. // injects a header or a whole request.
  9602. const std::string evil_targets[] = {
  9603. "/a\r\nInjected: pwned",
  9604. "/a\rInjected",
  9605. "/a\nInjected",
  9606. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9607. "/a b",
  9608. "/a\tb",
  9609. "/a\x7f",
  9610. };
  9611. for (const auto &evil : evil_targets) {
  9612. detail::BufferStream strm;
  9613. auto n = detail::write_request_line(strm, "GET", evil);
  9614. EXPECT_LT(n, 0);
  9615. EXPECT_TRUE(strm.get_buffer().empty());
  9616. }
  9617. }
  9618. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9619. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9620. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9621. // target reaches write_request. The client must fail cleanly with
  9622. // Error::Write instead of putting a request-line-less, header-injecting
  9623. // request on the wire.
  9624. Server svr;
  9625. svr.Get("/a", [](const Request &, Response &res) {
  9626. res.set_content("ok", "text/plain");
  9627. });
  9628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. thread.join();
  9632. ASSERT_FALSE(svr.is_running());
  9633. });
  9634. svr.wait_until_ready();
  9635. {
  9636. Client cli(HOST, PORT);
  9637. cli.set_path_encode(false);
  9638. // The request is rejected before anything is written, so the connection
  9639. // stays silent and the subsequent response read would otherwise block for
  9640. // the full default read timeout. Shorten it -- the assertion is on the
  9641. // error, not the timeout.
  9642. cli.set_read_timeout(1, 0);
  9643. auto res = cli.Get("/a\r\nInjected: pwned");
  9644. EXPECT_FALSE(res);
  9645. EXPECT_EQ(Error::Write, res.error());
  9646. }
  9647. }
  9648. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9649. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9650. // including extension methods.
  9651. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9652. for (const auto &method : good_methods) {
  9653. detail::BufferStream strm;
  9654. auto n = detail::write_request_line(strm, method, "/");
  9655. EXPECT_GT(n, 0);
  9656. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9657. }
  9658. // A method carrying CR/LF would split the request line and smuggle a whole
  9659. // request ahead of the real one. A space or an empty method corrupts the
  9660. // request line. All must be rejected before anything reaches the wire.
  9661. const std::string evil_methods[] = {
  9662. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9663. "GET\r\nInjected: pwned",
  9664. "GET\r",
  9665. "GET\n",
  9666. "GE T",
  9667. "",
  9668. };
  9669. for (const auto &evil : evil_methods) {
  9670. detail::BufferStream strm;
  9671. auto n = detail::write_request_line(strm, evil, "/");
  9672. EXPECT_LT(n, 0);
  9673. EXPECT_TRUE(strm.get_buffer().empty());
  9674. }
  9675. }
  9676. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9677. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9678. // through Client::send must fail with Error::Write and no request, neither
  9679. // the smuggled one nor the real one, may reach the server.
  9680. Server svr;
  9681. std::atomic<int> request_count(0);
  9682. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9683. request_count++;
  9684. res.status = StatusCode::OK_200;
  9685. return Server::HandlerResponse::Handled;
  9686. });
  9687. auto port = svr.bind_to_any_port(HOST);
  9688. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9689. auto se = detail::scope_exit([&] {
  9690. svr.stop();
  9691. thread.join();
  9692. ASSERT_FALSE(svr.is_running());
  9693. });
  9694. svr.wait_until_ready();
  9695. {
  9696. Client cli(HOST, port);
  9697. const std::string evil_methods[] = {
  9698. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9699. "GE T",
  9700. "",
  9701. };
  9702. for (const auto &evil : evil_methods) {
  9703. Request req;
  9704. req.method = evil;
  9705. req.path = "/";
  9706. auto res = cli.send(req);
  9707. EXPECT_FALSE(res);
  9708. EXPECT_EQ(Error::Write, res.error());
  9709. }
  9710. auto handle =
  9711. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9712. EXPECT_FALSE(handle.is_valid());
  9713. EXPECT_EQ(Error::Write, handle.error);
  9714. // A valid request on the same client still goes through.
  9715. auto res = cli.Get("/");
  9716. ASSERT_TRUE(res);
  9717. EXPECT_EQ(StatusCode::OK_200, res->status);
  9718. }
  9719. EXPECT_EQ(1, request_count.load());
  9720. }
  9721. // Sends a raw request and verifies that there isn't a crash or exception.
  9722. static void test_raw_request(const std::string &req,
  9723. std::string *out = nullptr) {
  9724. Server svr;
  9725. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9729. res.set_content("ok", "text/plain");
  9730. });
  9731. svr.Get("/header_field_value_check",
  9732. [&](const Request & /*req*/, Response &res) {
  9733. res.set_content("ok", "text/plain");
  9734. });
  9735. svr.CustomRoute("PROPFIND", "/dav",
  9736. [&](const Request & /*req*/, Response &res) {
  9737. res.status = StatusCode::MultiStatus_207;
  9738. });
  9739. // Server read timeout must be longer than the client read timeout for the
  9740. // bug to reproduce, probably to force the server to process a request
  9741. // without a trailing blank line.
  9742. const time_t client_read_timeout_sec = 1;
  9743. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9744. bool listen_thread_ok = false;
  9745. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. ASSERT_FALSE(svr.is_running());
  9750. EXPECT_TRUE(listen_thread_ok);
  9751. });
  9752. svr.wait_until_ready();
  9753. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9754. }
  9755. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9756. // A certain header line causes an exception if the header property is parsed
  9757. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9758. test_raw_request(
  9759. "GET /hi HTTP/1.1\r\n"
  9760. " : "
  9761. " "
  9762. " ");
  9763. }
  9764. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9765. // A certain header line causes an exception if the header property *name* is
  9766. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9767. // greedy matcher and requires backtracking when there are a lot of ":"
  9768. // characters.
  9769. // This occurs with libc++ but not libstdc++.
  9770. test_raw_request(
  9771. "GET /hi HTTP/1.1\r\n"
  9772. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9773. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9774. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9775. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9776. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9777. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9778. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9779. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9780. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9781. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9782. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9783. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9784. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9785. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9786. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9787. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9788. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9789. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9790. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9791. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9792. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9793. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9794. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9795. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9796. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9797. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9798. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9799. "&&&%%%");
  9800. }
  9801. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9802. // Make sure this doesn't crash the server.
  9803. // In a previous version of the header line regex, the "\r" rendered the line
  9804. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9805. // a new position where the leading white space ended and the field value
  9806. // began.
  9807. // The crash occurs with libc++ but not libstdc++.
  9808. test_raw_request("GET /hi HTTP/1.1\r\n"
  9809. "a:" +
  9810. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9811. "\r\n"
  9812. "\r\n");
  9813. }
  9814. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9815. const char *rejected[] = {
  9816. // RFC 9112 §3: one SP between the parts, and nothing else
  9817. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9819. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9820. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9821. // A request-target has no fragment
  9822. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9823. // An HTTP/1.1 request needs a Host
  9824. "GET /hi HTTP/1.1\r\n\r\n",
  9825. };
  9826. for (auto request : rejected) {
  9827. std::string out;
  9828. test_raw_request(request, &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9830. }
  9831. std::string out;
  9832. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9833. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9834. }
  9835. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9836. // RFC 9112 §6.1
  9837. const char *requests[] = {
  9838. "PUT /put_hi HTTP/1.1\r\n"
  9839. "Host: localhost\r\n"
  9840. "Content-Length: 0\r\n"
  9841. "Transfer-Encoding: chunked\r\n"
  9842. "\r\n"
  9843. "0\r\n\r\n",
  9844. "PUT /put_hi HTTP/1.0\r\n"
  9845. "Connection: keep-alive\r\n"
  9846. "Transfer-Encoding: chunked\r\n"
  9847. "\r\n"
  9848. "0\r\n\r\n",
  9849. };
  9850. for (auto request : requests) {
  9851. std::string out;
  9852. test_raw_request(request, &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9854. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9855. }
  9856. }
  9857. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9858. std::string out;
  9859. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9860. "Content-Type: text/plain\r\n"
  9861. "Transfer-Encoding: chunked\r\n"
  9862. "\r\n"
  9863. "nothex\r\n",
  9864. &out);
  9865. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9866. }
  9867. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9868. std::string out;
  9869. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9870. "Content-Type: text/plain\r\n"
  9871. "Transfer-Encoding: chunked\r\n"
  9872. "\r\n"
  9873. "3\r\n"
  9874. "xyz\r\n"
  9875. "NaN\r\n",
  9876. &out);
  9877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9878. }
  9879. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9880. std::string out;
  9881. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9882. "Content-Type: text/plain\r\n"
  9883. "Transfer-Encoding: chunked\r\n"
  9884. "\r\n"
  9885. // Length is too large for 64 bits.
  9886. "1ffffffffffffffff\r\n"
  9887. "xyz\r\n",
  9888. &out);
  9889. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9890. }
  9891. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9892. test_raw_request("GET /hi HTTP/1.1\r\n"
  9893. "Content-Type: text/plain\r\n\r");
  9894. }
  9895. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9896. std::string out;
  9897. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9899. }
  9900. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9901. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9902. std::string out;
  9903. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9904. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9905. }
  9906. }
  9907. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9908. std::string out;
  9909. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9910. "Host: localhost\r\n"
  9911. "Connection: close\r\n\r\n",
  9912. &out);
  9913. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9914. }
  9915. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9916. Server svr;
  9917. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9918. EXPECT_TRUE(!req.remote_addr.empty());
  9919. });
  9920. thread t = thread([&] { svr.listen(HOST, PORT); });
  9921. auto se = detail::scope_exit([&] {
  9922. svr.stop();
  9923. t.join();
  9924. ASSERT_FALSE(svr.is_running());
  9925. });
  9926. svr.wait_until_ready();
  9927. // Send an invalid request line to trigger Bad Request
  9928. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9929. std::string out;
  9930. ASSERT_TRUE(send_request(5, bad_req, &out));
  9931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9932. }
  9933. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9934. // answered right away rather than blocking on a read that waits for EOF.
  9935. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9936. std::string out;
  9937. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9938. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9939. }
  9940. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9941. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9942. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9943. for (const auto *method : methods) {
  9944. Server svr;
  9945. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9946. EXPECT_FALSE(svr.is_valid()) << method;
  9947. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9948. }
  9949. }
  9950. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9951. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9952. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9953. for (const auto *method : methods) {
  9954. Server svr;
  9955. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9956. EXPECT_FALSE(svr.is_valid()) << method;
  9957. }
  9958. }
  9959. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9960. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9961. "COPY", "MOVE", "LOCK",
  9962. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9963. Server svr;
  9964. for (const auto *method : methods) {
  9965. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9966. }
  9967. EXPECT_TRUE(svr.is_valid());
  9968. }
  9969. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9970. Server svr;
  9971. svr.CustomRoute("POST", "/x",
  9972. [](const Request &, Response &, const ContentReader &) {});
  9973. EXPECT_FALSE(svr.is_valid());
  9974. }
  9975. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9976. Server svr;
  9977. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9978. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9979. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9980. EXPECT_FALSE(svr.is_valid());
  9981. }
  9982. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9983. Server svr;
  9984. auto captured = Error::Success;
  9985. svr.set_error_logger(
  9986. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9987. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9988. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9989. }
  9990. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9991. std::string out;
  9992. std::string request(
  9993. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9994. test_raw_request(request, &out);
  9995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9996. }
  9997. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9998. std::string out;
  9999. std::string request(
  10000. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10001. test_raw_request(request, &out);
  10002. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10003. }
  10004. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10005. std::string out;
  10006. std::string request(
  10007. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10008. test_raw_request(request, &out);
  10009. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10010. }
  10011. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10012. std::string out;
  10013. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10014. "Host: localhost\r\n"
  10015. "Test: \r\n\r\n",
  10016. &out);
  10017. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10018. }
  10019. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10020. Server svr;
  10021. std::string x_custom;
  10022. std::string cookie;
  10023. std::string xff;
  10024. std::string x_unicode;
  10025. std::string x_iis;
  10026. svr.Get("/check", [&](const Request &req, Response &res) {
  10027. x_custom = req.get_header_value("X-Custom");
  10028. cookie = req.get_header_value("Cookie");
  10029. xff = req.get_header_value("X-Forwarded-For");
  10030. x_unicode = req.get_header_value("X-Unicode");
  10031. x_iis = req.get_header_value("X-IIS");
  10032. res.set_content("ok", "text/plain");
  10033. });
  10034. thread t = thread([&] { svr.listen(HOST, PORT); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. t.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. const std::string req = "GET /check HTTP/1.1\r\n"
  10042. "Host: localhost\r\n"
  10043. "X-Custom: a%0D%0AInjected: b\r\n"
  10044. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10045. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10046. "X-Unicode: %E3%81%82\r\n"
  10047. "X-IIS: %u00E9\r\n"
  10048. "Connection: close\r\n"
  10049. "\r\n";
  10050. std::string res;
  10051. ASSERT_TRUE(send_request(5, req, &res));
  10052. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10053. // Every value must be returned verbatim (wire form), with no decoding.
  10054. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10055. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10056. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10057. EXPECT_EQ("%E3%81%82", x_unicode);
  10058. EXPECT_EQ("%u00E9", x_iis);
  10059. }
  10060. // Applications that previously relied on automatic percent-decoding can
  10061. // reproduce the old behavior by explicitly calling decode_path_component()
  10062. // or, for RFC 3986 conformance, decode_uri_component().
  10063. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10064. Server svr;
  10065. std::string decoded;
  10066. svr.Get("/check", [&](const Request &req, Response &res) {
  10067. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10068. res.set_content("ok", "text/plain");
  10069. });
  10070. thread t = thread([&] { svr.listen(HOST, PORT); });
  10071. auto se = detail::scope_exit([&] {
  10072. svr.stop();
  10073. t.join();
  10074. ASSERT_FALSE(svr.is_running());
  10075. });
  10076. svr.wait_until_ready();
  10077. const std::string req = "GET /check HTTP/1.1\r\n"
  10078. "Host: localhost\r\n"
  10079. "X-Custom: hello%20world\r\n"
  10080. "Connection: close\r\n"
  10081. "\r\n";
  10082. std::string res;
  10083. ASSERT_TRUE(send_request(5, req, &res));
  10084. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10085. EXPECT_EQ("hello world", decoded);
  10086. }
  10087. // Regression test for #2033. Browsers send Referer values that include
  10088. // percent-encoded characters such as %0A inside the URL. Decoding the
  10089. // header value would either trip the post-decode CR/LF/NUL guard (the
  10090. // original bug, returning 400) or, after that guard was relaxed, silently
  10091. // store a literal LF — both unacceptable. The wire form must round-trip.
  10092. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10093. Server svr;
  10094. std::string referer;
  10095. svr.Get("/check", [&](const Request &req, Response &res) {
  10096. referer = req.get_header_value("Referer");
  10097. res.set_content("ok", "text/plain");
  10098. });
  10099. thread t = thread([&] { svr.listen(HOST, PORT); });
  10100. auto se = detail::scope_exit([&] {
  10101. svr.stop();
  10102. t.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. });
  10105. svr.wait_until_ready();
  10106. const std::string req = "GET /check HTTP/1.1\r\n"
  10107. "Host: localhost\r\n"
  10108. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10109. "Connection: close\r\n"
  10110. "\r\n";
  10111. std::string res;
  10112. ASSERT_TRUE(send_request(5, req, &res));
  10113. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10114. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10115. }
  10116. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10117. Server svr;
  10118. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10119. res.set_header("Cache-Control", "no-cache");
  10120. res.set_chunked_content_provider(
  10121. "text/event-stream", [](size_t offset, DataSink &sink) {
  10122. std::string s = "data:";
  10123. s += std::to_string(offset);
  10124. s += "\n\n";
  10125. auto ret = sink.write(s.data(), s.size());
  10126. EXPECT_TRUE(ret);
  10127. std::this_thread::sleep_for(std::chrono::seconds(1));
  10128. return true;
  10129. });
  10130. });
  10131. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10132. svr.wait_until_ready();
  10133. Client client(HOST, PORT);
  10134. const Headers headers = {{"Accept", "text/event-stream"}};
  10135. auto get_thread = std::thread([&client, &headers]() {
  10136. auto res = client.Get(
  10137. "/events", headers,
  10138. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10139. });
  10140. auto se = detail::scope_exit([&] {
  10141. svr.stop();
  10142. get_thread.join();
  10143. listen_thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. });
  10146. // Give GET time to get a few messages.
  10147. std::this_thread::sleep_for(std::chrono::seconds(2));
  10148. }
  10149. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10150. httplib::Server svr;
  10151. svr.Post("/hi",
  10152. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10153. res.status = StatusCode::OK_200;
  10154. });
  10155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10156. svr.wait_until_ready();
  10157. Client cli(HOST, PORT);
  10158. auto res = cli.Post("/hi", "data", "text/plain");
  10159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10160. EXPECT_EQ(StatusCode::OK_200, res->status);
  10161. svr.stop();
  10162. thread.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. res = cli.Post("/hi", "data", "text/plain");
  10165. ASSERT_FALSE(res);
  10166. }
  10167. TEST(ServerStopTest, ListenFailure) {
  10168. Server svr;
  10169. auto t = thread([&]() {
  10170. auto ret = svr.listen("????", PORT);
  10171. EXPECT_FALSE(ret);
  10172. });
  10173. svr.wait_until_ready();
  10174. svr.stop();
  10175. t.join();
  10176. }
  10177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10178. TEST(ServerStopTest, Decommision) {
  10179. Server svr;
  10180. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10181. for (int i = 0; i < 4; i++) {
  10182. auto is_even = !(i % 2);
  10183. std::thread t{[&] {
  10184. try {
  10185. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10186. if (is_even) {
  10187. throw std::runtime_error("Some thing that happens to go wrong.");
  10188. }
  10189. svr.listen(HOST, PORT);
  10190. } catch (...) { svr.decommission(); }
  10191. }};
  10192. svr.wait_until_ready();
  10193. // Server is up
  10194. {
  10195. Client cli(HOST, PORT);
  10196. auto res = cli.Get("/hi");
  10197. if (is_even) {
  10198. EXPECT_FALSE(res);
  10199. } else {
  10200. EXPECT_TRUE(res);
  10201. EXPECT_EQ("hi...", res->body);
  10202. }
  10203. }
  10204. svr.stop();
  10205. t.join();
  10206. // Server is down...
  10207. {
  10208. Client cli(HOST, PORT);
  10209. auto res = cli.Get("/hi");
  10210. EXPECT_FALSE(res);
  10211. }
  10212. }
  10213. }
  10214. #endif
  10215. // Helper function for string body upload progress tests
  10216. template <typename SetupHandler, typename ClientCall>
  10217. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10218. ClientCall &&client_call,
  10219. const string &body) {
  10220. Server svr;
  10221. setup_handler(svr);
  10222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10223. auto se = detail::scope_exit([&] {
  10224. svr.stop();
  10225. t.join();
  10226. });
  10227. svr.wait_until_ready();
  10228. Client cli(HOST, PORT);
  10229. vector<uint64_t> progress_values;
  10230. bool progress_called = false;
  10231. auto res =
  10232. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. progress_called = true;
  10235. return true;
  10236. });
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ(200, res->status);
  10239. EXPECT_TRUE(progress_called);
  10240. }
  10241. TEST(UploadProgressTest, PostStringBodyBasic) {
  10242. TestStringBodyUploadProgress(
  10243. [](Server &svr) {
  10244. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10245. res.set_content("received", "text/plain");
  10246. });
  10247. },
  10248. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10249. return cli.Post("/test", body, "text/plain", progress_callback);
  10250. },
  10251. "test data for upload progress");
  10252. }
  10253. TEST(UploadProgressTest, PutStringBodyBasic) {
  10254. TestStringBodyUploadProgress(
  10255. [](Server &svr) {
  10256. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10257. res.set_content("put received", "text/plain");
  10258. });
  10259. },
  10260. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10261. return cli.Put("/test", body, "text/plain", progress_callback);
  10262. },
  10263. "put test data for upload progress");
  10264. }
  10265. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10266. TestStringBodyUploadProgress(
  10267. [](Server &svr) {
  10268. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10269. res.set_content("patch received", "text/plain");
  10270. });
  10271. },
  10272. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10273. return cli.Patch("/test", body, "text/plain", progress_callback);
  10274. },
  10275. "patch test data for upload progress");
  10276. }
  10277. // Helper function for content provider upload progress tests
  10278. template <typename SetupHandler, typename ClientCall>
  10279. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10280. ClientCall &&client_call) {
  10281. Server svr;
  10282. setup_handler(svr);
  10283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10284. auto se = detail::scope_exit([&] {
  10285. svr.stop();
  10286. t.join();
  10287. });
  10288. svr.wait_until_ready();
  10289. Client cli(HOST, PORT);
  10290. vector<uint64_t> progress_values;
  10291. auto res =
  10292. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10293. progress_values.push_back(current);
  10294. return true;
  10295. });
  10296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10297. EXPECT_EQ(200, res->status);
  10298. EXPECT_FALSE(progress_values.empty());
  10299. }
  10300. TEST(UploadProgressTest, PostContentProviderProgress) {
  10301. TestContentProviderUploadProgress(
  10302. [](Server &svr) {
  10303. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10304. res.set_content("provider received", "text/plain");
  10305. });
  10306. },
  10307. [](Client &cli, UploadProgress progress_callback) {
  10308. return cli.Post(
  10309. "/test", 9,
  10310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10311. sink.os << "test data";
  10312. return true;
  10313. },
  10314. "text/plain", progress_callback);
  10315. });
  10316. }
  10317. // Helper function for multipart upload progress tests
  10318. template <typename SetupHandler, typename ClientCall>
  10319. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10320. ClientCall &&client_call,
  10321. const string &endpoint) {
  10322. Server svr;
  10323. setup_handler(svr);
  10324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10325. auto se = detail::scope_exit([&] {
  10326. svr.stop();
  10327. t.join();
  10328. });
  10329. svr.wait_until_ready();
  10330. Client cli(HOST, PORT);
  10331. vector<uint64_t> progress_values;
  10332. UploadFormDataItems items = {
  10333. {"field1", "value1", "", ""},
  10334. {"field2", "longer value for progress tracking test", "", ""},
  10335. {"file1", "file content data for upload progress", "test.txt",
  10336. "text/plain"}};
  10337. auto res = client_call(cli, endpoint, items,
  10338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10339. progress_values.push_back(current);
  10340. return true;
  10341. });
  10342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10343. EXPECT_EQ(200, res->status);
  10344. EXPECT_FALSE(progress_values.empty());
  10345. }
  10346. TEST(UploadProgressTest, PostMultipartProgress) {
  10347. TestMultipartUploadProgress(
  10348. [](Server &svr) {
  10349. svr.Post("/multipart", [](const Request &req, Response &res) {
  10350. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10351. res.set_content("multipart received", "text/plain");
  10352. });
  10353. },
  10354. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10355. UploadProgress progress_callback) {
  10356. return cli.Post(endpoint, items, progress_callback);
  10357. },
  10358. "/multipart");
  10359. }
  10360. // Helper function for basic download progress tests
  10361. template <typename SetupHandler, typename ClientCall>
  10362. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10363. ClientCall &&client_call, const string &endpoint,
  10364. size_t expected_content_size) {
  10365. Server svr;
  10366. setup_handler(svr);
  10367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10368. auto se = detail::scope_exit([&] {
  10369. svr.stop();
  10370. t.join();
  10371. });
  10372. svr.wait_until_ready();
  10373. Client cli(HOST, PORT);
  10374. vector<uint64_t> progress_values;
  10375. auto res = client_call(cli, endpoint,
  10376. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10377. progress_values.push_back(current);
  10378. return true;
  10379. });
  10380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10381. EXPECT_EQ(200, res->status);
  10382. EXPECT_FALSE(progress_values.empty());
  10383. EXPECT_EQ(expected_content_size, res->body.size());
  10384. }
  10385. TEST(DownloadProgressTest, GetBasic) {
  10386. TestBasicDownloadProgress(
  10387. [](Server &svr) {
  10388. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10389. string content(1000, 'D');
  10390. res.set_content(content, "text/plain");
  10391. });
  10392. },
  10393. [](Client &cli, const string &endpoint,
  10394. DownloadProgress progress_callback) {
  10395. return cli.Get(endpoint, progress_callback);
  10396. },
  10397. "/download", 1000u);
  10398. }
  10399. // Helper function for content receiver download progress tests
  10400. template <typename SetupHandler, typename ClientCall>
  10401. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10402. ClientCall &&client_call,
  10403. const string &endpoint,
  10404. size_t expected_content_size) {
  10405. Server svr;
  10406. setup_handler(svr);
  10407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10408. auto se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. t.join();
  10411. });
  10412. svr.wait_until_ready();
  10413. Client cli(HOST, PORT);
  10414. vector<uint64_t> progress_values;
  10415. string received_body;
  10416. auto res = client_call(
  10417. cli, endpoint,
  10418. [&](const char *data, size_t data_length) -> bool {
  10419. received_body.append(data, data_length);
  10420. return true;
  10421. },
  10422. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10423. progress_values.push_back(current);
  10424. return true;
  10425. });
  10426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10427. EXPECT_EQ(200, res->status);
  10428. EXPECT_FALSE(progress_values.empty());
  10429. EXPECT_EQ(expected_content_size, received_body.size());
  10430. EXPECT_TRUE(res->body.empty());
  10431. }
  10432. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10433. TestContentReceiverDownloadProgress(
  10434. [](Server &svr) {
  10435. svr.Get("/download-receiver",
  10436. [](const Request & /*req*/, Response &res) {
  10437. string content(2000, 'R');
  10438. res.set_content(content, "text/plain");
  10439. });
  10440. },
  10441. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10442. DownloadProgress progress_callback) {
  10443. return cli.Get(endpoint, content_receiver, progress_callback);
  10444. },
  10445. "/download-receiver", 2000u);
  10446. }
  10447. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10448. // A provider reaching a pass with nothing to hand over - an empty buffer
  10449. // popped off a queue, say - must not be taken to mean the body is finished.
  10450. // It used to end the loop with the terminating chunk unwritten while the
  10451. // server still considered the response complete, so the peer waited for an
  10452. // end that never arrived.
  10453. Server svr;
  10454. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10455. auto step = std::make_shared<int>(0);
  10456. res.set_chunked_content_provider("text/plain",
  10457. [step](size_t /*offset*/, DataSink &sink) {
  10458. switch ((*step)++) {
  10459. case 0: sink.write("", 0); break;
  10460. case 1: sink.write("hello", 5); break;
  10461. default: sink.done(); break;
  10462. }
  10463. return true;
  10464. });
  10465. });
  10466. auto port = svr.bind_to_any_port(HOST);
  10467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10468. auto listen_se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. listen_thread.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.wait_until_ready();
  10474. Client cli(HOST, port);
  10475. // Without the fix the body is never terminated, so bound the wait rather
  10476. // than letting the test hang on the default read timeout.
  10477. cli.set_read_timeout(5, 0);
  10478. auto res = cli.Get("/stream");
  10479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10480. EXPECT_EQ(StatusCode::OK_200, res->status);
  10481. EXPECT_EQ("hello", res->body);
  10482. }
  10483. TEST(StreamingTest, NoContentLengthStreaming) {
  10484. Server svr;
  10485. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10486. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10487. if (offset < 6) {
  10488. sink.os << (offset < 3 ? "a" : "b");
  10489. } else {
  10490. sink.done();
  10491. }
  10492. return true;
  10493. });
  10494. });
  10495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10496. auto listen_se = detail::scope_exit([&] {
  10497. svr.stop();
  10498. listen_thread.join();
  10499. ASSERT_FALSE(svr.is_running());
  10500. });
  10501. svr.wait_until_ready();
  10502. Client client(HOST, PORT);
  10503. auto get_thread = std::thread([&client]() {
  10504. std::string s;
  10505. auto res =
  10506. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10507. s += std::string(data, len);
  10508. return true;
  10509. });
  10510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10511. EXPECT_EQ(StatusCode::OK_200, res->status);
  10512. EXPECT_EQ("aaabbb", s);
  10513. });
  10514. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10515. // Give GET time to get a few messages.
  10516. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10517. }
  10518. TEST(MountTest, Unmount) {
  10519. Server svr;
  10520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10521. auto se = detail::scope_exit([&] {
  10522. svr.stop();
  10523. listen_thread.join();
  10524. ASSERT_FALSE(svr.is_running());
  10525. });
  10526. svr.wait_until_ready();
  10527. Client cli("localhost", PORT);
  10528. svr.set_mount_point("/mount2", "./www2");
  10529. auto res = cli.Get("/");
  10530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10532. res = cli.Get("/mount2/dir/test.html");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. svr.set_mount_point("/", "./www");
  10536. res = cli.Get("/dir/");
  10537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10538. EXPECT_EQ(StatusCode::OK_200, res->status);
  10539. svr.remove_mount_point("/");
  10540. res = cli.Get("/dir/");
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10543. svr.remove_mount_point("/mount2");
  10544. res = cli.Get("/mount2/dir/test.html");
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10547. }
  10548. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10549. Server svr;
  10550. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10551. svr.Get("/api/hello", [](const Request &, Response &res) {
  10552. res.set_content("api", "text/plain");
  10553. });
  10554. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. listen_thread.join();
  10558. ASSERT_FALSE(svr.is_running());
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, PORT);
  10562. auto res = cli.Get("/dir/test.html");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. res = cli.Get("/api/hello");
  10566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10567. EXPECT_EQ(StatusCode::OK_200, res->status);
  10568. EXPECT_EQ("api", res->body);
  10569. }
  10570. TEST(MountTest, PathSegmentBoundary) {
  10571. Server svr;
  10572. svr.set_mount_point("/mount2", "./www2");
  10573. svr.set_mount_point("/", "./www");
  10574. auto port = svr.bind_to_any_port(HOST);
  10575. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10576. auto se = detail::scope_exit([&] {
  10577. svr.stop();
  10578. listen_thread.join();
  10579. ASSERT_FALSE(svr.is_running());
  10580. });
  10581. svr.wait_until_ready();
  10582. Client cli(HOST, port);
  10583. auto res = cli.Get("/mount2/dir/test.html");
  10584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status);
  10586. // "/mount2" must not match part-way through a path segment.
  10587. res = cli.Get("/mount2dir/test.html");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10590. // A mount point ending in '/' keeps matching every path below it.
  10591. res = cli.Get("/dir/test.html");
  10592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10593. EXPECT_EQ(StatusCode::OK_200, res->status);
  10594. }
  10595. TEST(MountTest, Redicect) {
  10596. Server svr;
  10597. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. listen_thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.set_mount_point("/", "./www");
  10604. svr.wait_until_ready();
  10605. Client cli("localhost", PORT);
  10606. auto res = cli.Get("/dir/");
  10607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10608. EXPECT_EQ(StatusCode::OK_200, res->status);
  10609. res = cli.Get("/dir");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10612. res = cli.Get("/file");
  10613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10614. EXPECT_EQ(StatusCode::OK_200, res->status);
  10615. res = cli.Get("/file/");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10618. cli.set_follow_location(true);
  10619. res = cli.Get("/dir");
  10620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10621. EXPECT_EQ(StatusCode::OK_200, res->status);
  10622. }
  10623. TEST(MountTest, MultibytesPathName) {
  10624. Server svr;
  10625. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.set_mount_point("/", "./www");
  10632. svr.wait_until_ready();
  10633. Client cli("localhost", PORT);
  10634. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status);
  10637. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10638. }
  10639. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10640. // in the pre-routing handler sees the path of every file that is served
  10641. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10642. Server svr;
  10643. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10644. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10645. if (req.path == "/dir/test.html") {
  10646. res.status = StatusCode::Unauthorized_401;
  10647. return Server::HandlerResponse::Handled;
  10648. }
  10649. return Server::HandlerResponse::Unhandled;
  10650. });
  10651. auto port = svr.bind_to_any_port(HOST);
  10652. ASSERT_LT(0, port);
  10653. thread t = thread([&] { svr.listen_after_bind(); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. t.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.wait_until_ready();
  10660. Client cli(HOST, port);
  10661. for (auto path :
  10662. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10663. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10664. SCOPED_TRACE(path);
  10665. auto res = cli.Get(path);
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10668. }
  10669. }
  10670. #ifdef _WIN32
  10671. // Issue #2435: mmap::open() must succeed even when another handle holds
  10672. // the file open for writing (e.g. an active log file).
  10673. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10674. const char *path = "mmap_concurrent_writer_test.txt";
  10675. const char *content = "hello";
  10676. {
  10677. std::ofstream f(path, std::ios::binary);
  10678. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10679. }
  10680. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10681. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10682. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10683. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10684. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10685. detail::mmap m(path);
  10686. ASSERT_TRUE(m.is_open());
  10687. EXPECT_EQ(strlen(content), m.size());
  10688. char buf[8];
  10689. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10690. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10691. }
  10692. #endif
  10693. #ifndef _WIN32
  10694. // A directory or a device has no size to serve.
  10695. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10696. const char *path = "./mmap_not_regular_test_dir";
  10697. ASSERT_EQ(0, ::mkdir(path, 0755));
  10698. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10699. for (auto p : {path, "/dev/null"}) {
  10700. detail::mmap m(p);
  10701. EXPECT_FALSE(m.is_open()) << p;
  10702. EXPECT_EQ(0U, m.size()) << p;
  10703. }
  10704. Server svr;
  10705. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10706. res.set_file_content("/dev/null");
  10707. });
  10708. auto port = svr.bind_to_any_port(HOST);
  10709. thread t = thread([&] { svr.listen_after_bind(); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. t.join();
  10713. });
  10714. svr.wait_until_ready();
  10715. auto res = Client(HOST, port).Get("/null");
  10716. ASSERT_TRUE(res);
  10717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10718. }
  10719. #endif
  10720. #ifdef __linux__
  10721. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10722. TEST(MmapTest, FileIsNotMapped) {
  10723. const char *path = "mmap_not_mapped_test.txt";
  10724. {
  10725. std::ofstream f(path, std::ios::binary);
  10726. f << "hello";
  10727. }
  10728. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10729. detail::mmap m(path);
  10730. ASSERT_TRUE(m.is_open());
  10731. std::ifstream maps("/proc/self/maps");
  10732. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10733. std::istreambuf_iterator<char>());
  10734. EXPECT_EQ(std::string::npos, mappings.find(path));
  10735. }
  10736. #endif
  10737. TEST(KeepAliveTest, ReadTimeout) {
  10738. Server svr;
  10739. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10740. std::this_thread::sleep_for(std::chrono::seconds(2));
  10741. res.set_content("a", "text/plain");
  10742. });
  10743. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content("b", "text/plain");
  10745. });
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.wait_until_ready();
  10753. Client cli("localhost", PORT);
  10754. cli.set_keep_alive(true);
  10755. cli.set_read_timeout(std::chrono::seconds(1));
  10756. auto resa = cli.Get("/a");
  10757. ASSERT_FALSE(resa);
  10758. EXPECT_EQ(Error::Read, resa.error());
  10759. auto resb = cli.Get("/b");
  10760. ASSERT_TRUE(resb);
  10761. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10762. EXPECT_EQ("b", resb->body);
  10763. }
  10764. TEST(KeepAliveTest, MaxCount) {
  10765. size_t keep_alive_max_count = 3;
  10766. Server svr;
  10767. svr.set_keep_alive_max_count(keep_alive_max_count);
  10768. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10769. res.set_content("Hello World!", "text/plain");
  10770. });
  10771. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. listen_thread.join();
  10775. ASSERT_FALSE(svr.is_running());
  10776. });
  10777. svr.wait_until_ready();
  10778. Client cli(HOST, PORT);
  10779. cli.set_keep_alive(true);
  10780. for (size_t i = 0; i < 5; i++) {
  10781. auto result = cli.Get("/hi");
  10782. ASSERT_TRUE(result);
  10783. EXPECT_EQ(StatusCode::OK_200, result->status);
  10784. if (i == keep_alive_max_count - 1) {
  10785. EXPECT_EQ("close", result->get_header_value("Connection"));
  10786. } else {
  10787. EXPECT_FALSE(result->has_header("Connection"));
  10788. }
  10789. }
  10790. }
  10791. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10792. // can pull the next one into the server's buffer. The server must serve it
  10793. // without waiting for the socket to become readable again. The keep-alive
  10794. // timeout outlasts the client's read timeout, so a request left waiting for it
  10795. // shows up as a missing response.
  10796. static void serve_pipelining_routes(Server &svr,
  10797. const std::function<void(int)> &client) {
  10798. svr.set_keep_alive_timeout(5);
  10799. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10800. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10801. });
  10802. svr.Post("/echo", [](const Request &req, Response &res) {
  10803. res.set_content("echo " + req.body, "text/plain");
  10804. });
  10805. auto port = svr.bind_to_any_port(HOST);
  10806. thread t = thread([&] { svr.listen_after_bind(); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. t.join();
  10810. });
  10811. svr.wait_until_ready();
  10812. client(port);
  10813. }
  10814. static std::string
  10815. send_pipelined_requests(const std::vector<std::string> &parts) {
  10816. Server svr;
  10817. std::string res;
  10818. serve_pipelining_routes(svr, [&](int port) {
  10819. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10820. });
  10821. return res;
  10822. }
  10823. static void expect_in_order(const std::string &res,
  10824. const std::vector<std::string> &bodies) {
  10825. size_t pos = 0;
  10826. for (const auto &body : bodies) {
  10827. pos = res.find(body, pos);
  10828. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10829. pos += body.size();
  10830. }
  10831. }
  10832. TEST(KeepAliveTest, PipelinedRequests) {
  10833. auto res = send_pipelined_requests(
  10834. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10835. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10836. "Content-Length: 4\r\n\r\nbody"
  10837. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10838. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10839. }
  10840. // The second request starts in the server's buffer and ends on the socket.
  10841. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10842. auto res =
  10843. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10844. "GET /hi/2 HTTP/1.1\r\nHo",
  10845. "st: localhost\r\nConnection: close\r\n\r\n"});
  10846. expect_in_order(res, {"hi 1", "hi 2"});
  10847. }
  10848. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10849. // CRLF after a body does not turn into a 400 for the next request.
  10850. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10851. auto res = send_pipelined_requests(
  10852. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10853. "Content-Length: 4\r\n\r\nbody\r\n"
  10854. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10855. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10856. expect_in_order(res, {"echo body", "hi 2"});
  10857. }
  10858. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10859. // must not be served as the next request.
  10860. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10861. auto res = send_pipelined_requests(
  10862. {"INVALID REQUEST LINE\r\n\r\n"
  10863. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10864. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10865. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10866. }
  10867. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10868. // Over TLS, the next request is held by the TLS library as already decrypted
  10869. // data rather than on the socket.
  10870. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10872. std::string res;
  10873. serve_pipelining_routes(svr, [&](int port) {
  10874. // One part, so all three requests arrive in one TLS record
  10875. EXPECT_TRUE(send_ssl_request_in_parts(
  10876. 2,
  10877. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10878. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10879. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10880. &res, port));
  10881. });
  10882. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10883. }
  10884. #endif
  10885. TEST(KeepAliveTest, Issue1041) {
  10886. Server svr;
  10887. svr.set_keep_alive_timeout(3);
  10888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10889. res.set_content("Hello World!", "text/plain");
  10890. });
  10891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. Client cli(HOST, PORT);
  10899. cli.set_keep_alive(true);
  10900. auto result = cli.Get("/hi");
  10901. ASSERT_TRUE(result);
  10902. EXPECT_EQ(StatusCode::OK_200, result->status);
  10903. std::this_thread::sleep_for(std::chrono::seconds(5));
  10904. result = cli.Get("/hi");
  10905. ASSERT_TRUE(result);
  10906. EXPECT_EQ(StatusCode::OK_200, result->status);
  10907. }
  10908. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10909. Server svr;
  10910. svr.set_keep_alive_max_count(0);
  10911. std::set<int> remote_ports;
  10912. svr.Get("/hi", [&](const Request &req, Response &res) {
  10913. remote_ports.insert(req.remote_port);
  10914. res.set_content("hi", "text/plain");
  10915. });
  10916. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10917. auto se = detail::scope_exit([&] {
  10918. svr.stop();
  10919. listen_thread.join();
  10920. ASSERT_FALSE(svr.is_running());
  10921. });
  10922. svr.wait_until_ready();
  10923. Client cli(HOST, PORT);
  10924. cli.set_keep_alive(true);
  10925. for (int i = 0; i < 3; i++) {
  10926. auto res = cli.Get("/hi");
  10927. ASSERT_TRUE(res);
  10928. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10929. }
  10930. // All three over one connection
  10931. EXPECT_EQ(1u, remote_ports.size());
  10932. }
  10933. TEST(KeepAliveTest, Issue1959) {
  10934. Server svr;
  10935. svr.set_keep_alive_timeout(5);
  10936. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10937. res.set_content("a", "text/plain");
  10938. });
  10939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10940. auto se = detail::scope_exit([&] {
  10941. if (!svr.is_running()) return;
  10942. svr.stop();
  10943. listen_thread.join();
  10944. ASSERT_FALSE(svr.is_running());
  10945. });
  10946. svr.wait_until_ready();
  10947. Client cli("localhost", PORT);
  10948. cli.set_keep_alive(true);
  10949. using namespace std::chrono;
  10950. auto start = steady_clock::now();
  10951. cli.Get("/a");
  10952. svr.stop();
  10953. listen_thread.join();
  10954. auto end = steady_clock::now();
  10955. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10956. EXPECT_LT(elapsed, 5000);
  10957. }
  10958. #ifdef CPPHTTPLIB_SSL_ENABLED
  10959. TEST(KeepAliveTest, SSLClientReconnection) {
  10960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10961. ASSERT_TRUE(svr.is_valid());
  10962. svr.set_keep_alive_timeout(1);
  10963. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10964. res.set_content("Hello World!", "text/plain");
  10965. });
  10966. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10967. auto se = detail::scope_exit([&] {
  10968. svr.stop();
  10969. listen_thread.join();
  10970. ASSERT_FALSE(svr.is_running());
  10971. });
  10972. svr.wait_until_ready();
  10973. SSLClient cli(HOST, PORT);
  10974. cli.enable_server_certificate_verification(false);
  10975. cli.set_keep_alive(true);
  10976. auto result = cli.Get("/hi");
  10977. ASSERT_TRUE(result);
  10978. EXPECT_EQ(StatusCode::OK_200, result->status);
  10979. result = cli.Get("/hi");
  10980. ASSERT_TRUE(result);
  10981. EXPECT_EQ(StatusCode::OK_200, result->status);
  10982. std::this_thread::sleep_for(std::chrono::seconds(2));
  10983. // Recoonect
  10984. result = cli.Get("/hi");
  10985. ASSERT_TRUE(result);
  10986. EXPECT_EQ(StatusCode::OK_200, result->status);
  10987. result = cli.Get("/hi");
  10988. ASSERT_TRUE(result);
  10989. EXPECT_EQ(StatusCode::OK_200, result->status);
  10990. }
  10991. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10993. ASSERT_TRUE(svr.is_valid());
  10994. svr.set_keep_alive_timeout(1);
  10995. std::string content = "reconnect";
  10996. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10997. res.set_content("Hello World!", "text/plain");
  10998. });
  10999. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. listen_thread.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. });
  11005. svr.wait_until_ready();
  11006. SSLClient cli(HOST, PORT);
  11007. cli.enable_server_certificate_verification(false);
  11008. cli.set_keep_alive(true);
  11009. auto result = cli.Post(
  11010. "/hi", content.size(),
  11011. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11012. sink.write(content.c_str(), content.size());
  11013. return true;
  11014. },
  11015. "text/plain");
  11016. ASSERT_TRUE(result);
  11017. EXPECT_EQ(200, result->status);
  11018. std::this_thread::sleep_for(std::chrono::seconds(2));
  11019. // Recoonect
  11020. result = cli.Post(
  11021. "/hi", content.size(),
  11022. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11023. sink.write(content.c_str(), content.size());
  11024. return true;
  11025. },
  11026. "text/plain");
  11027. ASSERT_TRUE(result);
  11028. EXPECT_EQ(200, result->status);
  11029. result = cli.Post(
  11030. "/hi", content.size(),
  11031. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11032. sink.write(content.c_str(), content.size());
  11033. return true;
  11034. },
  11035. "text/plain");
  11036. ASSERT_TRUE(result);
  11037. EXPECT_EQ(200, result->status);
  11038. }
  11039. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11040. using namespace httplib::tls;
  11041. {
  11042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11043. ASSERT_TRUE(svr.is_valid());
  11044. svr.Get("/sni", [&](const Request &req, Response &res) {
  11045. std::string expected = req.sni();
  11046. EXPECT_EQ(expected, req.get_param_value("expected"));
  11047. res.set_content("ok", "text/plain");
  11048. });
  11049. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. listen_thread.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. {
  11057. SSLClient cli("localhost", PORT);
  11058. cli.enable_server_certificate_verification(false);
  11059. auto res = cli.Get("/sni?expected=localhost");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. }
  11062. {
  11063. SSLClient cli("::1", PORT);
  11064. cli.enable_server_certificate_verification(false);
  11065. auto res = cli.Get("/sni?expected=");
  11066. // NOTE: This may fail if the server is listening on IPv4 only
  11067. // (e.g., when localhost resolves to 127.0.0.1 only)
  11068. if (res) {
  11069. EXPECT_EQ(StatusCode::OK_200, res->status);
  11070. } else {
  11071. EXPECT_EQ(Error::Connection, res.error());
  11072. }
  11073. }
  11074. }
  11075. }
  11076. // The SNI of a failed handshake does not reach the next connection that the
  11077. // same worker thread serves
  11078. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11079. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11080. ASSERT_TRUE(svr.is_valid());
  11081. svr.new_task_queue = [] { return new ThreadPool(1); };
  11082. svr.Get("/sni", [](const Request &req, Response &res) {
  11083. res.set_content(req.sni(), "text/plain");
  11084. });
  11085. auto port = svr.bind_to_any_port("127.0.0.1");
  11086. ASSERT_LT(0, port);
  11087. thread t = thread([&] { svr.listen_after_bind(); });
  11088. auto se = detail::scope_exit([&] {
  11089. svr.stop();
  11090. t.join();
  11091. ASSERT_FALSE(svr.is_running());
  11092. });
  11093. svr.wait_until_ready();
  11094. {
  11095. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11096. SSLClient cli("localhost", port);
  11097. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11098. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11099. auto res = cli.Get("/sni");
  11100. ASSERT_FALSE(res);
  11101. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11102. }
  11103. // An IP host sends no SNI (RFC 6066)
  11104. SSLClient cli("127.0.0.1", port);
  11105. cli.enable_server_certificate_verification(false);
  11106. auto res = cli.Get("/sni");
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. EXPECT_EQ("", res->body);
  11109. }
  11110. #endif
  11111. TEST(ClientProblemDetectionTest, ContentProvider) {
  11112. Server svr;
  11113. size_t content_length = 1024 * 1024;
  11114. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11115. res.set_content_provider(
  11116. content_length, "text/plain",
  11117. [&](size_t offset, size_t length, DataSink &sink) {
  11118. auto out_len = std::min(length, static_cast<size_t>(1024));
  11119. std::string out(out_len, '@');
  11120. sink.write(out.data(), out_len);
  11121. return offset < 4096;
  11122. },
  11123. [](bool success) { ASSERT_FALSE(success); });
  11124. });
  11125. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11126. res.set_content_provider(
  11127. 0, "text/plain",
  11128. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11129. EXPECT_TRUE(false);
  11130. return true;
  11131. },
  11132. [](bool success) { ASSERT_FALSE(success); });
  11133. });
  11134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11135. auto se = detail::scope_exit([&] {
  11136. svr.stop();
  11137. listen_thread.join();
  11138. ASSERT_FALSE(svr.is_running());
  11139. });
  11140. svr.wait_until_ready();
  11141. Client cli("localhost", PORT);
  11142. {
  11143. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11144. size_t /*data_length*/) { return false; });
  11145. ASSERT_FALSE(res);
  11146. }
  11147. {
  11148. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11149. size_t /*data_length*/) { return false; });
  11150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11151. }
  11152. }
  11153. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11154. // A provider that reports success without writing anything and without
  11155. // calling done() used to be handed the same offset and length again on every
  11156. // pass, so it spun for as long as the peer stayed connected.
  11157. Server svr;
  11158. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11159. res.set_content("ok", "text/plain");
  11160. });
  11161. auto port = svr.bind_to_any_port(HOST);
  11162. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11163. auto se = detail::scope_exit([&] {
  11164. svr.stop();
  11165. listen_thread.join();
  11166. ASSERT_FALSE(svr.is_running());
  11167. });
  11168. svr.wait_until_ready();
  11169. std::atomic<int> call_count{0};
  11170. Client cli(HOST, port);
  11171. auto res = cli.Post(
  11172. "/", 1024,
  11173. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11174. // Give up after enough passes to show the spin, so that losing the
  11175. // check below fails this test instead of hanging it.
  11176. return ++call_count < 100;
  11177. },
  11178. "text/plain");
  11179. ASSERT_FALSE(res);
  11180. EXPECT_EQ(Error::Write, res.error());
  11181. EXPECT_EQ(1, call_count.load());
  11182. }
  11183. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11184. // A writer only has to assign `write`. The other three used to be left as
  11185. // empty std::functions, so a provider calling one threw
  11186. // std::bad_function_call out of the thread running it and took the whole
  11187. // process down.
  11188. DataSink sink;
  11189. std::string written;
  11190. sink.write = [&](const char *data, size_t data_len) {
  11191. written.append(data, data_len);
  11192. return true;
  11193. };
  11194. EXPECT_TRUE(sink.is_writable());
  11195. sink.done();
  11196. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11197. EXPECT_TRUE(written.empty());
  11198. }
  11199. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11200. // A sink that cannot carry trailers still has to finish.
  11201. DataSink sink;
  11202. auto done_count = 0;
  11203. sink.done = [&]() { done_count++; };
  11204. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11205. EXPECT_EQ(1, done_count);
  11206. }
  11207. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11208. Server svr;
  11209. const std::string body(4096, 'x');
  11210. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11211. res.set_content_provider(body.size(), "text/plain",
  11212. [&](size_t offset, size_t length, DataSink &sink) {
  11213. sink.write(body.data() + offset, length);
  11214. sink.done();
  11215. return true;
  11216. });
  11217. });
  11218. auto port = svr.bind_to_any_port(HOST);
  11219. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. listen_thread.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. Client cli(HOST, port);
  11227. auto res = cli.Get("/");
  11228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11229. EXPECT_EQ(StatusCode::OK_200, res->status);
  11230. EXPECT_EQ(body, res->body);
  11231. }
  11232. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11233. Server svr;
  11234. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11235. res.set_content_provider(
  11236. 1024, "text/plain",
  11237. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11238. sink.write("hello", 5);
  11239. sink.done(); // short of the 1024 bytes the response promised
  11240. return true;
  11241. });
  11242. });
  11243. auto port = svr.bind_to_any_port(HOST);
  11244. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. listen_thread.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, port);
  11252. cli.set_read_timeout(5, 0);
  11253. // The response is short of its Content-Length, so the client cannot read a
  11254. // complete body. What matters is that this returns at all: a no-op done()
  11255. // would leave the writer looping over a provider that never makes progress.
  11256. auto res = cli.Get("/");
  11257. EXPECT_FALSE(res);
  11258. }
  11259. // Read as the next response by a peer that sees it after a framed body.
  11260. static const std::string smuggled_response =
  11261. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11262. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11263. Server svr;
  11264. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11265. res.set_content_provider(
  11266. 5, "text/plain",
  11267. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11268. auto data = "AAAAA" + smuggled_response;
  11269. sink.write(data.data(), data.size());
  11270. return true;
  11271. });
  11272. });
  11273. thread t = thread([&] { svr.listen(HOST, PORT); });
  11274. auto se = detail::scope_exit([&] {
  11275. svr.stop();
  11276. t.join();
  11277. ASSERT_FALSE(svr.is_running());
  11278. });
  11279. svr.wait_until_ready();
  11280. std::string resp;
  11281. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11282. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11283. resp.clear();
  11284. ASSERT_TRUE(send_request(
  11285. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11286. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11287. }
  11288. TEST(NoContentTest, BodyIsNotSent) {
  11289. Server svr;
  11290. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11291. res.status = StatusCode::NoContent_204;
  11292. res.set_content(smuggled_response, "text/plain");
  11293. });
  11294. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11295. res.status = StatusCode::NotModified_304;
  11296. res.set_chunked_content_provider(
  11297. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11298. sink.write(smuggled_response.data(), smuggled_response.size());
  11299. sink.done();
  11300. return true;
  11301. });
  11302. });
  11303. thread t = thread([&] { svr.listen(HOST, PORT); });
  11304. auto se = detail::scope_exit([&] {
  11305. svr.stop();
  11306. t.join();
  11307. ASSERT_FALSE(svr.is_running());
  11308. });
  11309. svr.wait_until_ready();
  11310. for (auto path : {"/204", "/304"}) {
  11311. std::string resp;
  11312. ASSERT_TRUE(send_request(
  11313. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11314. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11315. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11316. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11317. }
  11318. }
  11319. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11320. Server svr;
  11321. std::atomic<bool> smuggled(false);
  11322. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11323. res.set_content("ok", "text/plain");
  11324. });
  11325. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11326. smuggled = true;
  11327. });
  11328. auto port = svr.bind_to_any_port(HOST);
  11329. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11330. auto se = detail::scope_exit([&] {
  11331. svr.stop();
  11332. listen_thread.join();
  11333. ASSERT_FALSE(svr.is_running());
  11334. });
  11335. svr.wait_until_ready();
  11336. // What follows the body would be read as the next request.
  11337. Client cli(HOST, port);
  11338. auto res = cli.Post(
  11339. "/", 5,
  11340. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11341. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11342. sink.write(data.data(), data.size());
  11343. return true;
  11344. },
  11345. "text/plain");
  11346. ASSERT_FALSE(res);
  11347. EXPECT_EQ(Error::Write, res.error());
  11348. EXPECT_FALSE(smuggled);
  11349. }
  11350. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11351. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11352. // The compressed path builds the whole body before connecting, so this
  11353. // fails client-side and never reaches a server.
  11354. Client cli(HOST, PORT);
  11355. cli.set_compress(true);
  11356. auto res = cli.Post(
  11357. "/", 1024,
  11358. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11359. sink.write("hello", 5);
  11360. sink.done(); // short of the 1024 bytes the request announced
  11361. return true;
  11362. },
  11363. "text/plain");
  11364. ASSERT_FALSE(res);
  11365. EXPECT_EQ(Error::Write, res.error());
  11366. }
  11367. #endif
  11368. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11369. Server svr;
  11370. svr.set_error_handler([](Request const &, Response &res) -> void {
  11371. res.set_chunked_content_provider(
  11372. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11373. sink.os << "hello";
  11374. sink.os << "world";
  11375. sink.done();
  11376. return true;
  11377. });
  11378. });
  11379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11380. auto se = detail::scope_exit([&] {
  11381. svr.stop();
  11382. listen_thread.join();
  11383. ASSERT_FALSE(svr.is_running());
  11384. });
  11385. svr.wait_until_ready();
  11386. Client cli("localhost", PORT);
  11387. auto res = cli.Get("/");
  11388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11390. EXPECT_EQ("helloworld", res->body);
  11391. }
  11392. // A body set after a content provider must replace it, not be sent through it.
  11393. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11394. Server svr;
  11395. svr.set_mount_point("/", "./www");
  11396. svr.set_file_request_handler([](const Request &req, Response &res) {
  11397. if (req.path == "/dir/test.html") {
  11398. res.status = StatusCode::Forbidden_403;
  11399. res.set_content(std::string(5000, 'D'), "text/plain");
  11400. } else if (req.path == "/file") {
  11401. res.status = StatusCode::Forbidden_403;
  11402. res.body = "Denied";
  11403. }
  11404. });
  11405. auto port = svr.bind_to_any_port(HOST);
  11406. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11407. auto se = detail::scope_exit([&] {
  11408. svr.stop();
  11409. t.join();
  11410. ASSERT_FALSE(svr.is_running());
  11411. });
  11412. svr.wait_until_ready();
  11413. Client cli(HOST, port);
  11414. {
  11415. auto res = cli.Get("/dir/test.html");
  11416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11417. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11418. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11419. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11420. }
  11421. {
  11422. auto res = cli.Get("/file");
  11423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11424. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11425. EXPECT_EQ("Denied", res->body);
  11426. }
  11427. {
  11428. auto res = cli.Get("/dir/index.html");
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. EXPECT_EQ(StatusCode::OK_200, res->status);
  11431. EXPECT_EQ(0U, res->body.find("<html>"));
  11432. }
  11433. }
  11434. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11435. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11436. Server svr;
  11437. std::vector<bool> released;
  11438. std::mutex released_mutex;
  11439. auto releaser = [&](bool success) {
  11440. std::lock_guard<std::mutex> guard(released_mutex);
  11441. released.push_back(success);
  11442. };
  11443. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11444. return sink.write(&"hello"[offset], length);
  11445. };
  11446. svr.Get("/sized", [&](const Request &, Response &res) {
  11447. res.status = StatusCode::NotFound_404;
  11448. res.set_content_provider(5, "text/plain", provider, releaser);
  11449. });
  11450. svr.Get("/chunked", [&](const Request &, Response &res) {
  11451. res.status = StatusCode::ServiceUnavailable_503;
  11452. res.set_chunked_content_provider(
  11453. "text/plain",
  11454. [](size_t, DataSink &sink) {
  11455. sink.os << "chunk";
  11456. sink.done();
  11457. return true;
  11458. },
  11459. releaser);
  11460. });
  11461. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11462. res.set_content_provider(5, "text/plain", provider, releaser);
  11463. throw std::runtime_error("after the provider");
  11464. });
  11465. svr.set_error_handler([](const Request &req, Response &res) {
  11466. // Leave the exception handler's content to it.
  11467. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11468. res.set_content(std::string(1000, 'E'), "text/html");
  11469. return Server::HandlerResponse::Handled;
  11470. });
  11471. svr.set_exception_handler(
  11472. [](const Request &, Response &res, std::exception_ptr) {
  11473. res.status = StatusCode::InternalServerError_500;
  11474. res.set_content(std::string(1000, 'X'), "text/html");
  11475. });
  11476. auto port = svr.bind_to_any_port(HOST);
  11477. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. t.join();
  11481. ASSERT_FALSE(svr.is_running());
  11482. });
  11483. svr.wait_until_ready();
  11484. Client cli(HOST, port);
  11485. {
  11486. auto res = cli.Get("/sized");
  11487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11489. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11490. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11491. }
  11492. {
  11493. auto res = cli.Get("/chunked");
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11496. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11497. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11498. }
  11499. {
  11500. auto res = cli.Get("/throw");
  11501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11503. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11504. }
  11505. std::lock_guard<std::mutex> guard(released_mutex);
  11506. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11507. }
  11508. #endif
  11509. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11510. Server svr;
  11511. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11512. return sink.write(&"abc"[offset], length);
  11513. };
  11514. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11515. res.set_file_content("./www/dir/test.html");
  11516. res.set_content("body", "text/plain");
  11517. });
  11518. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11519. res.set_content(std::string(100, 'B'), "text/plain");
  11520. res.set_file_content("./www/dir/test.html");
  11521. });
  11522. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11523. res.set_content(std::string(100, 'B'), "text/plain");
  11524. res.set_content_provider(3, "text/x-provider", abc);
  11525. });
  11526. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11527. res.set_content_provider(3, "text/x-provider", abc);
  11528. res.set_content(std::string(100, 'B'), "text/plain");
  11529. });
  11530. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11531. res.set_content_provider(3, "text/x-provider", abc);
  11532. res.set_file_content("./www/dir/test.html", "text/x-file");
  11533. });
  11534. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11535. res.set_file_content("./www/dir/test.html");
  11536. res.set_header("Content-Type", "text/x-handler");
  11537. });
  11538. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11539. res.set_content_provider(3, "text/plain", abc);
  11540. res.body = "direct";
  11541. });
  11542. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11543. res.set_file_content("./www/dir/test.html");
  11544. res.body = "direct";
  11545. });
  11546. auto port = svr.bind_to_any_port(HOST);
  11547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11548. auto se = detail::scope_exit([&] {
  11549. svr.stop();
  11550. t.join();
  11551. ASSERT_FALSE(svr.is_running());
  11552. });
  11553. svr.wait_until_ready();
  11554. Client cli(HOST, port);
  11555. auto expect_body = [&](const char *path, const std::string &body,
  11556. const std::string &type) {
  11557. // Uncompressed, so Content-Length can be compared with the body.
  11558. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11559. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11560. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11561. EXPECT_EQ(body, res->body) << path;
  11562. EXPECT_EQ(std::to_string(body.size()),
  11563. res->get_header_value("Content-Length"))
  11564. << path;
  11565. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11566. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11567. };
  11568. expect_body("/file-then-body", "body", "text/plain");
  11569. expect_body("/body-then-file", "test.html", "text/html");
  11570. expect_body("/body-then-provider", "abc", "text/x-provider");
  11571. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11572. expect_body("/provider-then-file", "test.html", "text/x-file");
  11573. expect_body("/file-then-header", "test.html", "text/x-handler");
  11574. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11575. expect_body("/file-then-direct-body", "direct", "text/plain");
  11576. // Ranges are checked against the body, not the dropped provider.
  11577. {
  11578. auto res = cli.Get("/provider-then-direct-body",
  11579. Headers{{make_range_header({{1, 2}})}});
  11580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11581. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11582. EXPECT_EQ("ir", res->body);
  11583. }
  11584. {
  11585. auto res = cli.Get("/file-then-direct-body",
  11586. Headers{{make_range_header({{7, 8}})}});
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11589. }
  11590. }
  11591. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11592. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11593. const char *path = "./truncated_while_served.txt";
  11594. const size_t size = 32 * 1024 * 1024;
  11595. {
  11596. std::ofstream f(path, std::ios::binary);
  11597. f << std::string(size, 'x');
  11598. }
  11599. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11600. // Over TLS, where the bytes are encrypted in this process rather than
  11601. // copied by send().
  11602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11603. svr.Get("/file", [&](const Request &, Response &res) {
  11604. res.set_file_content(path, "text/plain");
  11605. });
  11606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11607. auto se = detail::scope_exit([&] {
  11608. svr.stop();
  11609. thread.join();
  11610. ASSERT_FALSE(svr.is_running());
  11611. });
  11612. svr.wait_until_ready();
  11613. // The file shrinks once the first bytes are in, as a rewrite in place
  11614. // would, and reading the mapping past its new end used to raise SIGBUS.
  11615. SSLClient cli(HOST, PORT);
  11616. cli.enable_server_certificate_verification(false);
  11617. size_t received = 0;
  11618. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11619. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11620. received += len;
  11621. return true;
  11622. });
  11623. EXPECT_FALSE(res);
  11624. EXPECT_LT(received, size);
  11625. }
  11626. #endif
  11627. // Forward declaration (see the base64_encode note).
  11628. namespace httplib {
  11629. namespace detail {
  11630. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11631. const std::string &content_type,
  11632. EncodingType encoding);
  11633. } // namespace detail
  11634. } // namespace httplib
  11635. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11636. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11637. ASSERT_TRUE(mm->is_open());
  11638. Response res;
  11639. detail::set_file_content_provider(res, mm, "text/html",
  11640. detail::EncodingType::None);
  11641. std::string out;
  11642. DataSink sink;
  11643. sink.write = [&](const char *d, size_t l) {
  11644. out.append(d, l);
  11645. return true;
  11646. };
  11647. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11648. EXPECT_EQ("test.html", out);
  11649. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11650. EXPECT_EQ("test.html", out);
  11651. }
  11652. TEST(LongPollingTest, ClientCloseDetection) {
  11653. Server svr;
  11654. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11655. res.set_chunked_content_provider(
  11656. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11657. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11658. sink.os << "hello";
  11659. auto count = 10;
  11660. while (count > 0 && sink.is_writable()) {
  11661. this_thread::sleep_for(chrono::milliseconds(10));
  11662. count--;
  11663. }
  11664. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11665. return true;
  11666. });
  11667. });
  11668. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11669. auto se = detail::scope_exit([&] {
  11670. svr.stop();
  11671. listen_thread.join();
  11672. ASSERT_FALSE(svr.is_running());
  11673. });
  11674. svr.wait_until_ready();
  11675. Client cli("localhost", PORT);
  11676. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11677. EXPECT_EQ("hello", string(data, data_length));
  11678. return false; // close the socket immediately.
  11679. });
  11680. ASSERT_FALSE(res);
  11681. }
  11682. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11683. Server svr;
  11684. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11685. res.set_chunked_content_provider(
  11686. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11687. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11688. sink.os << "hello";
  11689. EXPECT_TRUE(sink.os.good());
  11690. // Wait for the client to close the connection
  11691. auto count = 10;
  11692. while (count > 0 && sink.is_writable()) {
  11693. this_thread::sleep_for(chrono::milliseconds(10));
  11694. count--;
  11695. }
  11696. // After client disconnect, write repeatedly until the socket
  11697. // write actually fails (small writes may be absorbed by the
  11698. // kernel buffer)
  11699. std::string chunk(1024, 'x');
  11700. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11701. sink.os << chunk;
  11702. }
  11703. EXPECT_TRUE(sink.os.fail());
  11704. return true;
  11705. });
  11706. });
  11707. auto port = svr.bind_to_any_port("localhost");
  11708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. listen_thread.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. Client cli("localhost", port);
  11716. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11717. EXPECT_EQ("hello", string(data, data_length));
  11718. return false; // close the socket immediately.
  11719. });
  11720. ASSERT_FALSE(res);
  11721. }
  11722. TEST(GetWithParametersTest, GetWithParameters) {
  11723. Server svr;
  11724. svr.Get("/", [&](const Request &req, Response &) {
  11725. EXPECT_EQ("world", req.get_param_value("hello"));
  11726. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11727. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11728. });
  11729. svr.Get("/params", [&](const Request &req, Response &) {
  11730. EXPECT_EQ("world", req.get_param_value("hello"));
  11731. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11732. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11733. });
  11734. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11735. EXPECT_EQ("resource-id", req.matches[1]);
  11736. EXPECT_EQ("foo", req.get_param_value("param1"));
  11737. EXPECT_EQ("bar", req.get_param_value("param2"));
  11738. });
  11739. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11740. EXPECT_EQ("user-id", req.path_params.at("id"));
  11741. EXPECT_EQ("foo", req.get_param_value("param1"));
  11742. EXPECT_EQ("bar", req.get_param_value("param2"));
  11743. });
  11744. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11745. auto se = detail::scope_exit([&] {
  11746. svr.stop();
  11747. listen_thread.join();
  11748. ASSERT_FALSE(svr.is_running());
  11749. });
  11750. svr.wait_until_ready();
  11751. {
  11752. Client cli(HOST, PORT);
  11753. Params params;
  11754. params.emplace("hello", "world");
  11755. params.emplace("hello2", "world2");
  11756. params.emplace("hello3", "world3");
  11757. auto res = cli.Get("/", params, Headers{});
  11758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11759. EXPECT_EQ(StatusCode::OK_200, res->status);
  11760. }
  11761. {
  11762. Client cli(HOST, PORT);
  11763. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11765. EXPECT_EQ(StatusCode::OK_200, res->status);
  11766. }
  11767. {
  11768. Client cli(HOST, PORT);
  11769. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11771. EXPECT_EQ(StatusCode::OK_200, res->status);
  11772. }
  11773. {
  11774. Client cli(HOST, PORT);
  11775. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11777. EXPECT_EQ(StatusCode::OK_200, res->status);
  11778. }
  11779. }
  11780. TEST(GetWithParametersTest, GetWithParameters2) {
  11781. Server svr;
  11782. svr.Get("/", [&](const Request &req, Response &res) {
  11783. auto text = req.get_param_value("hello");
  11784. res.set_content(text, "text/plain");
  11785. });
  11786. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11787. auto se = detail::scope_exit([&] {
  11788. svr.stop();
  11789. listen_thread.join();
  11790. ASSERT_FALSE(svr.is_running());
  11791. });
  11792. svr.wait_until_ready();
  11793. Client cli("localhost", PORT);
  11794. Params params;
  11795. params.emplace("hello", "world");
  11796. std::string body;
  11797. auto res = cli.Get("/", params, Headers{},
  11798. [&](const char *data, size_t data_length) {
  11799. body.append(data, data_length);
  11800. return true;
  11801. });
  11802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11803. EXPECT_EQ(StatusCode::OK_200, res->status);
  11804. EXPECT_EQ("world", body);
  11805. }
  11806. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11807. Server svr;
  11808. svr.Get("/search", [&](const Request &req, Response &res) {
  11809. auto q = req.get_param_value("q");
  11810. res.set_content(q, "text/plain");
  11811. });
  11812. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11813. auto se = detail::scope_exit([&] {
  11814. svr.stop();
  11815. listen_thread.join();
  11816. ASSERT_FALSE(svr.is_running());
  11817. });
  11818. svr.wait_until_ready();
  11819. Client cli("localhost", PORT);
  11820. // Verify that Get(path, params) works without requiring Headers argument
  11821. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. EXPECT_EQ("cpp-httplib", res->body);
  11825. }
  11826. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11827. auto host = "httpbingo.org";
  11828. auto path = std::string{"/range/32"};
  11829. #ifdef CPPHTTPLIB_SSL_ENABLED
  11830. SSLClient cli(host);
  11831. #else
  11832. Client cli(host);
  11833. #endif
  11834. cli.set_default_headers({make_range_header({{1, 10}})});
  11835. cli.set_connection_timeout(5);
  11836. {
  11837. auto res = cli.Get(path);
  11838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11839. EXPECT_EQ("bcdefghijk", res->body);
  11840. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11841. }
  11842. {
  11843. auto res = cli.Get(path);
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ("bcdefghijk", res->body);
  11846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11847. }
  11848. }
  11849. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11850. Server svr;
  11851. svr.set_default_headers({{"Hello", "World"}});
  11852. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11853. res.set_content("ok", "text/plain");
  11854. });
  11855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11856. auto se = detail::scope_exit([&] {
  11857. svr.stop();
  11858. listen_thread.join();
  11859. ASSERT_FALSE(svr.is_running());
  11860. });
  11861. svr.wait_until_ready();
  11862. Client cli("localhost", PORT);
  11863. auto res = cli.Get("/");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. EXPECT_EQ("ok", res->body);
  11867. EXPECT_EQ("World", res->get_header_value("Hello"));
  11868. }
  11869. #ifdef CPPHTTPLIB_SSL_ENABLED
  11870. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11872. ASSERT_TRUE(svr.is_valid());
  11873. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11874. std::this_thread::sleep_for(std::chrono::seconds(2));
  11875. res.set_content("a", "text/plain");
  11876. });
  11877. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11878. res.set_content("b", "text/plain");
  11879. });
  11880. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11881. auto se = detail::scope_exit([&] {
  11882. svr.stop();
  11883. listen_thread.join();
  11884. ASSERT_FALSE(svr.is_running());
  11885. });
  11886. svr.wait_until_ready();
  11887. SSLClient cli("localhost", PORT);
  11888. cli.enable_server_certificate_verification(false);
  11889. cli.set_keep_alive(true);
  11890. cli.set_read_timeout(std::chrono::seconds(1));
  11891. auto resa = cli.Get("/a");
  11892. ASSERT_TRUE(!resa);
  11893. EXPECT_EQ(Error::Read, resa.error());
  11894. auto resb = cli.Get("/b");
  11895. ASSERT_TRUE(resb);
  11896. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11897. EXPECT_EQ("b", resb->body);
  11898. }
  11899. // Closing an idle keep-alive connection sends close_notify and returns. The
  11900. // server must not wait for the client's close_notify: an idle client never
  11901. // sends one, so the worker would be held until the read timeout expires, and
  11902. // stop() would wait for it.
  11903. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11905. ASSERT_TRUE(svr.is_valid());
  11906. svr.set_keep_alive_timeout(1);
  11907. svr.set_read_timeout(10, 0);
  11908. svr.Get("/", [](const Request &, Response &res) {
  11909. res.set_content("ok", "text/plain");
  11910. });
  11911. auto port = svr.bind_to_any_port(HOST);
  11912. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11913. auto se = detail::scope_exit([&] {
  11914. if (listen_thread.joinable()) {
  11915. svr.stop();
  11916. listen_thread.join();
  11917. }
  11918. });
  11919. svr.wait_until_ready();
  11920. SSLClient cli(HOST, port);
  11921. cli.enable_server_certificate_verification(false);
  11922. cli.set_keep_alive(true);
  11923. auto res = cli.Get("/");
  11924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11925. EXPECT_EQ(StatusCode::OK_200, res->status);
  11926. // Stay idle past the keep-alive timeout so the server closes the connection.
  11927. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11928. auto start = std::chrono::steady_clock::now();
  11929. svr.stop();
  11930. listen_thread.join();
  11931. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11932. std::chrono::steady_clock::now() - start)
  11933. .count();
  11934. EXPECT_LT(elapsed, 3000);
  11935. }
  11936. #endif
  11937. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11938. protected:
  11939. ServerTestWithAI_PASSIVE()
  11940. : cli_(HOST, PORT)
  11941. #ifdef CPPHTTPLIB_SSL_ENABLED
  11942. ,
  11943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11944. #endif
  11945. {
  11946. #ifdef CPPHTTPLIB_SSL_ENABLED
  11947. cli_.enable_server_certificate_verification(false);
  11948. #endif
  11949. }
  11950. virtual void SetUp() {
  11951. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11952. res.set_content("Hello World!", "text/plain");
  11953. });
  11954. t_ = thread(
  11955. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11956. svr_.wait_until_ready();
  11957. }
  11958. virtual void TearDown() {
  11959. svr_.stop();
  11960. t_.join();
  11961. }
  11962. #ifdef CPPHTTPLIB_SSL_ENABLED
  11963. SSLClient cli_;
  11964. SSLServer svr_;
  11965. #else
  11966. Client cli_;
  11967. Server svr_;
  11968. #endif
  11969. thread t_;
  11970. };
  11971. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11972. auto res = cli_.Get("/hi");
  11973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11974. EXPECT_EQ(StatusCode::OK_200, res->status);
  11975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11976. EXPECT_EQ("Hello World!", res->body);
  11977. }
  11978. class ServerUpDownTest : public ::testing::Test {
  11979. protected:
  11980. ServerUpDownTest() : cli_(HOST, PORT) {}
  11981. virtual void SetUp() {
  11982. t_ = thread([&]() {
  11983. svr_.bind_to_any_port(HOST);
  11984. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11985. ASSERT_TRUE(svr_.listen_after_bind());
  11986. });
  11987. svr_.wait_until_ready();
  11988. }
  11989. virtual void TearDown() {
  11990. svr_.stop();
  11991. t_.join();
  11992. }
  11993. Client cli_;
  11994. Server svr_;
  11995. thread t_;
  11996. };
  11997. TEST_F(ServerUpDownTest, QuickStartStop) {
  11998. // Should not crash, especially when run with
  11999. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12000. }
  12001. class PayloadMaxLengthTest : public ::testing::Test {
  12002. protected:
  12003. PayloadMaxLengthTest()
  12004. : cli_(HOST, PORT)
  12005. #ifdef CPPHTTPLIB_SSL_ENABLED
  12006. ,
  12007. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12008. #endif
  12009. {
  12010. #ifdef CPPHTTPLIB_SSL_ENABLED
  12011. cli_.enable_server_certificate_verification(false);
  12012. #endif
  12013. }
  12014. virtual void SetUp() {
  12015. svr_.set_payload_max_length(8);
  12016. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12017. res.set_content("test", "text/plain");
  12018. });
  12019. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12020. svr_.wait_until_ready();
  12021. }
  12022. virtual void TearDown() {
  12023. svr_.stop();
  12024. t_.join();
  12025. }
  12026. #ifdef CPPHTTPLIB_SSL_ENABLED
  12027. SSLClient cli_;
  12028. SSLServer svr_;
  12029. #else
  12030. Client cli_;
  12031. Server svr_;
  12032. #endif
  12033. thread t_;
  12034. };
  12035. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12036. auto res = cli_.Post("/test", "123456789", "text/plain");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12039. res = cli_.Post("/test", "12345678", "text/plain");
  12040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12041. EXPECT_EQ(StatusCode::OK_200, res->status);
  12042. }
  12043. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12044. // Test chunked encoding with payload exceeding the 8-byte limit
  12045. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12046. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12049. }
  12050. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12051. // Test chunked encoding with payload within the 8-byte limit
  12052. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12053. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12055. EXPECT_EQ(StatusCode::OK_200, res->status);
  12056. }
  12057. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12058. // Test using send_request to send chunked data exceeding payload limit
  12059. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12060. "Host: " +
  12061. std::string(HOST) + ":" + std::to_string(PORT) +
  12062. "\r\n"
  12063. "Transfer-Encoding: chunked\r\n"
  12064. "Connection: close\r\n"
  12065. "\r\n"
  12066. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12067. "0123456789\r\n"
  12068. "0\r\n" // End chunk
  12069. "\r\n";
  12070. std::string response;
  12071. bool result = send_request(1, chunked_request, &response);
  12072. if (!result) {
  12073. // If send_request fails, it might be because the server closed the
  12074. // connection due to payload limit enforcement, which is acceptable
  12075. SUCCEED()
  12076. << "Server rejected oversized chunked request (connection closed)";
  12077. } else {
  12078. // If we got a response, check if it's an error response or connection was
  12079. // closed early Short response length indicates connection was closed due to
  12080. // payload limit
  12081. if (response.length() <= 10) {
  12082. SUCCEED() << "Server closed connection for oversized chunked request";
  12083. } else {
  12084. // Check for error status codes
  12085. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12086. response.find("Payload Too Large") != std::string::npos ||
  12087. response.find("400") != std::string::npos);
  12088. }
  12089. }
  12090. }
  12091. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12092. // Test request without Content-Length header exceeding payload limit
  12093. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12094. "Host: " +
  12095. std::string(HOST) + ":" +
  12096. std::to_string(PORT) +
  12097. "\r\n"
  12098. "Connection: close\r\n"
  12099. "\r\n";
  12100. // Add payload exceeding the 8-byte limit
  12101. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12102. request_without_content_length += large_payload;
  12103. std::string response;
  12104. bool result = send_request(1, request_without_content_length, &response);
  12105. if (!result) {
  12106. // If send_request fails, server likely closed connection due to payload
  12107. // limit
  12108. SUCCEED() << "Server rejected oversized request without Content-Length "
  12109. "(connection closed)";
  12110. } else {
  12111. // Check if server responded with error or closed connection early
  12112. if (response.length() <= 10) {
  12113. SUCCEED() << "Server closed connection for oversized request without "
  12114. "Content-Length";
  12115. } else {
  12116. // Check for error status codes
  12117. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12118. response.find("Payload Too Large") != std::string::npos ||
  12119. response.find("400") != std::string::npos);
  12120. }
  12121. }
  12122. }
  12123. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12124. // Test request without Content-Length header within payload limit
  12125. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12126. "Host: " +
  12127. std::string(HOST) + ":" +
  12128. std::to_string(PORT) +
  12129. "\r\n"
  12130. "Connection: close\r\n"
  12131. "\r\n";
  12132. // Add payload within the 8-byte limit
  12133. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12134. request_without_content_length += small_payload;
  12135. std::string response;
  12136. bool result = send_request(1, request_without_content_length, &response);
  12137. // For requests without Content-Length, the server may have different behavior
  12138. // The key is that it should not reject due to payload limit for small
  12139. // payloads
  12140. if (result) {
  12141. // Check for any HTTP response (success or error, but not connection closed)
  12142. if (response.length() > 10) {
  12143. SUCCEED()
  12144. << "Server processed request without Content-Length within limit";
  12145. } else {
  12146. // Short response might indicate connection closed, which is acceptable
  12147. SUCCEED() << "Server closed connection for request without "
  12148. "Content-Length (acceptable behavior)";
  12149. }
  12150. } else {
  12151. // Connection failure might be due to protocol requirements
  12152. SUCCEED() << "Connection issue with request without Content-Length "
  12153. "(environment-specific)";
  12154. }
  12155. }
  12156. class LargePayloadMaxLengthTest : public ::testing::Test {
  12157. protected:
  12158. LargePayloadMaxLengthTest()
  12159. : cli_(HOST, PORT)
  12160. #ifdef CPPHTTPLIB_SSL_ENABLED
  12161. ,
  12162. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12163. #endif
  12164. {
  12165. #ifdef CPPHTTPLIB_SSL_ENABLED
  12166. cli_.enable_server_certificate_verification(false);
  12167. #endif
  12168. }
  12169. virtual void SetUp() {
  12170. // Set 10MB payload limit
  12171. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12172. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12173. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12174. res.set_content("Large payload test", "text/plain");
  12175. });
  12176. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12177. svr_.wait_until_ready();
  12178. }
  12179. virtual void TearDown() {
  12180. svr_.stop();
  12181. t_.join();
  12182. }
  12183. #ifdef CPPHTTPLIB_SSL_ENABLED
  12184. SSLClient cli_;
  12185. SSLServer svr_;
  12186. #else
  12187. Client cli_;
  12188. Server svr_;
  12189. #endif
  12190. thread t_;
  12191. };
  12192. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12193. // Test chunked encoding with payload within 10MB limit
  12194. std::string medium_payload(5 * 1024 * 1024,
  12195. 'A'); // 5MB payload, within 10MB limit
  12196. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12198. EXPECT_EQ(StatusCode::OK_200, res->status);
  12199. }
  12200. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12201. // Test chunked encoding with payload exceeding 10MB limit
  12202. std::string large_payload(12 * 1024 * 1024,
  12203. 'B'); // 12MB payload, exceeds 10MB limit
  12204. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12205. // Server may either return 413 or close the connection
  12206. if (res) {
  12207. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12208. } else {
  12209. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12210. }
  12211. }
  12212. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12213. // Test request without Content-Length header within 10MB limit
  12214. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12215. "Host: " +
  12216. std::string(HOST) + ":" +
  12217. std::to_string(PORT) +
  12218. "\r\n"
  12219. "Connection: close\r\n"
  12220. "\r\n";
  12221. // Add 1MB payload (within 10MB limit)
  12222. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12223. request_without_content_length += medium_payload;
  12224. std::string response;
  12225. bool result = send_request(5, request_without_content_length, &response);
  12226. if (result) {
  12227. // Should get a proper HTTP response for payloads within limit
  12228. if (response.length() > 10) {
  12229. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12230. "10MB limit";
  12231. } else {
  12232. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12233. "Content-Length)";
  12234. }
  12235. } else {
  12236. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12237. }
  12238. }
  12239. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12240. // Test request without Content-Length header exceeding 10MB limit
  12241. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12242. "Host: " +
  12243. std::string(HOST) + ":" +
  12244. std::to_string(PORT) +
  12245. "\r\n"
  12246. "Connection: close\r\n"
  12247. "\r\n";
  12248. // Add 12MB payload (exceeds 10MB limit)
  12249. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12250. request_without_content_length += large_payload;
  12251. std::string response;
  12252. bool result = send_request(10, request_without_content_length, &response);
  12253. if (!result) {
  12254. // Server should close connection due to payload limit
  12255. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12256. "(connection closed)";
  12257. } else {
  12258. // Check for error response
  12259. if (response.length() <= 10) {
  12260. SUCCEED()
  12261. << "Server closed connection for 12MB request exceeding 10MB limit";
  12262. } else {
  12263. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12264. response.find("Payload Too Large") != std::string::npos ||
  12265. response.find("400") != std::string::npos);
  12266. }
  12267. }
  12268. }
  12269. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12270. Server svr;
  12271. svr.Get("/", [](const Request &, Response &res) {
  12272. // Claims the most the client accepts, far more than it sends, then drops
  12273. // the connection.
  12274. res.set_content_provider(std::string().max_size(), "text/plain",
  12275. [](size_t, size_t, DataSink &sink) {
  12276. sink.write("abc", 3);
  12277. return false;
  12278. });
  12279. });
  12280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12281. auto se = detail::scope_exit([&] {
  12282. svr.stop();
  12283. thread.join();
  12284. ASSERT_FALSE(svr.is_running());
  12285. });
  12286. svr.wait_until_ready();
  12287. Client cli(HOST, PORT);
  12288. cli.set_payload_max_length(0);
  12289. EXPECT_FALSE(cli.Get("/"));
  12290. }
  12291. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12292. // Stream API does, not as a plain read failure
  12293. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12294. Server svr;
  12295. svr.Get("/big", [](const Request &, Response &res) {
  12296. res.set_content(std::string(100000, 'b'), "text/plain");
  12297. });
  12298. auto port = svr.bind_to_any_port(HOST);
  12299. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12300. auto se = detail::scope_exit([&] {
  12301. svr.stop();
  12302. thread.join();
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, port);
  12306. cli.set_payload_max_length(1000);
  12307. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12308. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12309. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12310. [](const char *, size_t) { return true; });
  12311. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12312. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12313. // Small on the wire, over the limit once decompressed
  12314. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12315. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12316. #endif
  12317. }
  12318. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12319. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12320. // path.
  12321. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12322. Server svr;
  12323. const size_t LIMIT = 64 * 1024; // 64KB
  12324. svr.set_payload_max_length(LIMIT);
  12325. size_t total = 0;
  12326. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12327. const ContentReader &content_reader) {
  12328. content_reader([&](const char * /*data*/, size_t len) {
  12329. total += len;
  12330. return true;
  12331. });
  12332. res.status = 200;
  12333. res.set_content("stream_ok", "text/plain");
  12334. });
  12335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. thread.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. // Prepare 256KB raw data and gzip-compress it
  12343. std::string raw(256 * 1024, 'A');
  12344. std::string gz;
  12345. {
  12346. z_stream zs{};
  12347. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12348. Z_DEFAULT_STRATEGY);
  12349. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12350. zs.avail_in = static_cast<uInt>(raw.size());
  12351. char outbuf[4096];
  12352. int ret;
  12353. do {
  12354. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12355. zs.avail_out = sizeof(outbuf);
  12356. ret = deflate(&zs, Z_FINISH);
  12357. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12358. } while (ret != Z_STREAM_END);
  12359. deflateEnd(&zs);
  12360. }
  12361. Client cli(HOST, PORT);
  12362. cli.set_connection_timeout(std::chrono::seconds(5));
  12363. Headers headers = {{"Content-Encoding", "gzip"}};
  12364. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12365. "application/octet-stream");
  12366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12367. // Server must reject oversized decompressed payloads with 413.
  12368. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12369. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12370. EXPECT_LE(total, LIMIT);
  12371. }
  12372. #ifndef CPPHTTPLIB_SSL_ENABLED
  12373. // For a request with neither Content-Length nor Transfer-Encoding, the
  12374. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12375. // compressed wire bytes straight to the ContentReader without ever routing
  12376. // them through the decompressor, so payload_max_length_ only bounded the
  12377. // compressed size on the wire, not the decompressed size.
  12378. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12379. Server svr;
  12380. const size_t LIMIT = 64 * 1024; // 64KB
  12381. svr.set_payload_max_length(LIMIT);
  12382. size_t total = 0;
  12383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12384. const ContentReader &content_reader) {
  12385. content_reader([&](const char * /*data*/, size_t len) {
  12386. total += len;
  12387. return true;
  12388. });
  12389. res.status = 200;
  12390. res.set_content("stream_ok", "text/plain");
  12391. });
  12392. auto port = svr.bind_to_any_port(HOST);
  12393. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12394. auto se = detail::scope_exit([&] {
  12395. svr.stop();
  12396. thread.join();
  12397. ASSERT_FALSE(svr.is_running());
  12398. });
  12399. svr.wait_until_ready();
  12400. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12401. // StreamingGzipDecompression test above.
  12402. std::string raw(256 * 1024, 'A');
  12403. std::string gz;
  12404. {
  12405. httplib::detail::gzip_compressor compressor;
  12406. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12407. [&](const char *chunk, size_t len) {
  12408. gz.append(chunk, len);
  12409. return true;
  12410. });
  12411. ASSERT_TRUE(result);
  12412. }
  12413. // Send the gzip body over raw TCP with neither Content-Length nor
  12414. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12415. // kicks in.
  12416. std::string req = "POST /stream HTTP/1.1\r\n"
  12417. "Host: " +
  12418. std::string(HOST) + ":" + std::to_string(port) +
  12419. "\r\n"
  12420. "Content-Encoding: gzip\r\n"
  12421. "Connection: close\r\n"
  12422. "\r\n" +
  12423. gz;
  12424. std::string response;
  12425. ASSERT_TRUE(send_request(5, req, &response, port));
  12426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12427. EXPECT_LE(total, LIMIT);
  12428. }
  12429. #endif
  12430. #endif
  12431. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12432. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12433. // the payload must be passed through untouched instead of being rejected.
  12434. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12435. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12436. Server svr;
  12437. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12438. res.set_content(body, "image/jpeg");
  12439. res.set_header("Content-Encoding", "UTF-8");
  12440. });
  12441. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12442. res.set_content(body, "image/jpeg");
  12443. res.set_header("Content-Encoding", "identity");
  12444. });
  12445. svr.Post("/echo", [](const Request &req, Response &res) {
  12446. res.set_content(req.body, "image/jpeg");
  12447. });
  12448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12449. auto se = detail::scope_exit([&] {
  12450. svr.stop();
  12451. t.join();
  12452. ASSERT_FALSE(svr.is_running());
  12453. });
  12454. svr.wait_until_ready();
  12455. Client cli(HOST, PORT);
  12456. {
  12457. auto res = cli.Get("/image");
  12458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12459. EXPECT_EQ(StatusCode::OK_200, res->status);
  12460. EXPECT_EQ(body, res->body);
  12461. }
  12462. {
  12463. auto res = cli.Get("/identity");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. EXPECT_EQ(StatusCode::OK_200, res->status);
  12466. EXPECT_EQ(body, res->body);
  12467. }
  12468. {
  12469. // The same applies to a request body reaching the server.
  12470. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12471. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. EXPECT_EQ(StatusCode::OK_200, res->status);
  12474. EXPECT_EQ(body, res->body);
  12475. }
  12476. }
  12477. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12478. // gzip-encoded response even when the build has no zlib support.
  12479. static const char GZIPPED_HELLO_WORLD[] = {
  12480. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12481. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12482. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12483. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12484. // A content coding is a whole token, not something the field value merely
  12485. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12486. // as "fibre" look like Brotli, and turned a multi-coding value like
  12487. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12488. // it was never meant to see.
  12489. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12490. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12491. Server svr;
  12492. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12493. res.set_content(body, "image/jpeg");
  12494. res.set_header("Content-Encoding", "fibre");
  12495. });
  12496. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12497. res.set_content(body, "image/jpeg");
  12498. res.set_header("Content-Encoding", "gzip, br");
  12499. });
  12500. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12501. res.set_content(body, "image/jpeg");
  12502. res.set_header("Content-Encoding", "x-zstd-ish");
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. thread t = thread([&]() { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, port);
  12513. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12514. auto res = cli.Get(path);
  12515. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12516. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12517. // Not a coding we recognize, so the payload comes back untouched
  12518. EXPECT_EQ(body, res->body) << path;
  12519. }
  12520. }
  12521. // A content coding cpp-httplib recognizes but was not built with must be
  12522. // reported as such. Handing the still-compressed payload back to the caller
  12523. // would silently corrupt it.
  12524. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12525. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12526. Server svr;
  12527. // "image/jpeg" keeps the server from applying a content coding of its own,
  12528. // so the hand-crafted Content-Encoding below survives.
  12529. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12530. res.set_content(gzipped, "image/jpeg");
  12531. res.set_header("Content-Encoding", "gzip");
  12532. });
  12533. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12534. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12535. res.set_content(gzipped, "image/jpeg");
  12536. res.set_header("Content-Encoding", "GZIP");
  12537. });
  12538. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12539. auto se = detail::scope_exit([&] {
  12540. svr.stop();
  12541. t.join();
  12542. ASSERT_FALSE(svr.is_running());
  12543. });
  12544. svr.wait_until_ready();
  12545. Client cli(HOST, PORT);
  12546. {
  12547. auto res = cli.Get("/gzipped");
  12548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12550. EXPECT_EQ("Hello World!", res->body);
  12551. #else
  12552. ASSERT_FALSE(res);
  12553. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12554. #endif
  12555. }
  12556. {
  12557. // open_stream() must behave the same way.
  12558. auto handle = cli.open_stream("GET", "/gzipped");
  12559. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12560. ASSERT_TRUE(handle.is_valid());
  12561. std::string received;
  12562. char buf[256];
  12563. ssize_t n;
  12564. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12565. received.append(buf, static_cast<size_t>(n));
  12566. }
  12567. EXPECT_EQ("Hello World!", received);
  12568. #else
  12569. EXPECT_FALSE(handle.is_valid());
  12570. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12571. #endif
  12572. }
  12573. {
  12574. // A differently-cased coding must not be mistaken for an unknown one, or
  12575. // the body would be handed back still compressed.
  12576. auto res = cli.Get("/gzipped-uppercase");
  12577. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12579. EXPECT_EQ("Hello World!", res->body);
  12580. #else
  12581. ASSERT_FALSE(res);
  12582. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12583. #endif
  12584. }
  12585. }
  12586. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12587. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12588. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12589. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12590. // body a second time and appending a second Content-Encoding field line, so
  12591. // clients that decode one coding per listed value handed back raw gzip bytes.
  12592. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12593. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12594. Server svr;
  12595. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12596. // keeps the server from applying a coding of its own.
  12597. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12598. res.set_content(gzipped, "text/plain");
  12599. res.set_header("Content-Encoding", "gzip");
  12600. });
  12601. auto port = svr.bind_to_any_port(HOST);
  12602. thread t = thread([&]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. t.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. Client cli(HOST, port);
  12610. Headers headers = {{"Accept-Encoding", "gzip"}};
  12611. auto res = cli.Get("/pre-gzipped", headers);
  12612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12613. EXPECT_EQ(StatusCode::OK_200, res->status);
  12614. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12615. EXPECT_EQ("Hello World!", res->body);
  12616. }
  12617. // set_compress(false) sends every handler response as it is, buffered or
  12618. // streamed
  12619. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12620. const std::string text(1000, 'a');
  12621. Server svr;
  12622. svr.set_compress(false);
  12623. svr.Get("/buffered", [&](const Request &, Response &res) {
  12624. res.set_content(text, "text/plain");
  12625. });
  12626. svr.Get("/streamed", [&](const Request &, Response &res) {
  12627. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12628. sink.write(text.data(), text.size());
  12629. sink.done();
  12630. return true;
  12631. });
  12632. });
  12633. auto port = svr.bind_to_any_port(HOST);
  12634. ASSERT_LT(0, port);
  12635. thread t = thread([&] { svr.listen_after_bind(); });
  12636. auto se = detail::scope_exit([&] {
  12637. svr.stop();
  12638. t.join();
  12639. ASSERT_FALSE(svr.is_running());
  12640. });
  12641. svr.wait_until_ready();
  12642. Client cli(HOST, port);
  12643. cli.set_decompress(false);
  12644. for (auto path : {"/buffered", "/streamed"}) {
  12645. SCOPED_TRACE(path);
  12646. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12648. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12649. EXPECT_EQ(text, res->body);
  12650. }
  12651. }
  12652. // A chunked provider settles its coding where the headers are written and
  12653. // reuses it at write time. Both ends of that have to hold: a handler's own
  12654. // Content-Encoding suppresses the coding, and a response without one is still
  12655. // compressed as it always was.
  12656. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12657. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12658. const std::string plain = "Hello World! Hello World! Hello World!";
  12659. Server svr;
  12660. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12661. res.set_header("Content-Encoding", "gzip");
  12662. res.set_chunked_content_provider(
  12663. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12664. sink.write(gzipped.data(), gzipped.size());
  12665. sink.done();
  12666. return true;
  12667. });
  12668. });
  12669. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12670. res.set_chunked_content_provider(
  12671. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12672. sink.write(plain.data(), plain.size());
  12673. sink.done();
  12674. return true;
  12675. });
  12676. });
  12677. auto port = svr.bind_to_any_port(HOST);
  12678. thread t = thread([&]() { svr.listen_after_bind(); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. t.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. });
  12684. svr.wait_until_ready();
  12685. Client cli(HOST, port);
  12686. Headers headers = {{"Accept-Encoding", "gzip"}};
  12687. {
  12688. auto res = cli.Get("/pre-gzipped", headers);
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. EXPECT_EQ(StatusCode::OK_200, res->status);
  12691. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12692. EXPECT_EQ("Hello World!", res->body);
  12693. }
  12694. {
  12695. auto res = cli.Get("/negotiated", headers);
  12696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12697. EXPECT_EQ(StatusCode::OK_200, res->status);
  12698. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12699. EXPECT_EQ(plain, res->body);
  12700. }
  12701. }
  12702. #endif
  12703. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12704. // the same message as the comma-joined one, so both have to be read the same
  12705. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12706. // single gzip coding, and a body the sender says was encoded twice was handed
  12707. // back after one pass, still compressed but presented as decoded.
  12708. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12709. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12710. Server svr;
  12711. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12712. res.set_content(body, "image/jpeg");
  12713. res.headers.emplace("Content-Encoding", "gzip");
  12714. res.headers.emplace("Content-Encoding", "gzip");
  12715. });
  12716. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12717. res.set_content(body, "image/jpeg");
  12718. res.set_header("Content-Encoding", "gzip, gzip");
  12719. });
  12720. auto port = svr.bind_to_any_port(HOST);
  12721. thread t = thread([&]() { svr.listen_after_bind(); });
  12722. auto se = detail::scope_exit([&] {
  12723. svr.stop();
  12724. t.join();
  12725. ASSERT_FALSE(svr.is_running());
  12726. });
  12727. svr.wait_until_ready();
  12728. Client cli(HOST, port);
  12729. // Two codings is not something cpp-httplib decodes, so both representations
  12730. // take the pass-through path rather than one of them being gunzipped once.
  12731. for (const char *path : {"/split", "/joined"}) {
  12732. auto res = cli.Get(path);
  12733. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12734. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12735. EXPECT_EQ(body, res->body) << path;
  12736. }
  12737. }
  12738. // Regression test for DoS vulnerability: a malicious server sending a response
  12739. // without Content-Length header must not cause unbounded memory consumption on
  12740. // the client side. The client should stop reading after a reasonable limit,
  12741. // similar to the server-side set_payload_max_length protection.
  12742. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12743. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12744. #ifndef _WIN32
  12745. signal(SIGPIPE, SIG_IGN);
  12746. #endif
  12747. auto server_thread = std::thread([] {
  12748. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12750. default_socket_options(srv);
  12751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12753. sockaddr_in addr{};
  12754. addr.sin_family = AF_INET;
  12755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12757. int opt = 1;
  12758. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12759. #ifdef _WIN32
  12760. reinterpret_cast<const char *>(&opt),
  12761. #else
  12762. &opt,
  12763. #endif
  12764. sizeof(opt));
  12765. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12766. ::listen(srv, 1);
  12767. sockaddr_in cli_addr{};
  12768. socklen_t cli_len = sizeof(cli_addr);
  12769. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12770. if (cli != INVALID_SOCKET) {
  12771. char buf[4096];
  12772. ::recv(cli, buf, sizeof(buf), 0);
  12773. // Malicious response: no Content-Length, no chunked encoding
  12774. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12775. "Connection: close\r\n"
  12776. "\r\n";
  12777. ::send(cli,
  12778. #ifdef _WIN32
  12779. static_cast<const char *>(response_header.c_str()),
  12780. static_cast<int>(response_header.size()),
  12781. #else
  12782. response_header.c_str(), response_header.size(),
  12783. #endif
  12784. 0);
  12785. // Send 10MB of data
  12786. std::string chunk(64 * 1024, 'A');
  12787. size_t total_sent = 0;
  12788. while (total_sent < MALICIOUS_DATA_SIZE) {
  12789. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12790. auto sent = ::send(cli,
  12791. #ifdef _WIN32
  12792. static_cast<const char *>(chunk.c_str()),
  12793. static_cast<int>(to_send),
  12794. #else
  12795. chunk.c_str(), to_send,
  12796. #endif
  12797. 0);
  12798. if (sent <= 0) break;
  12799. total_sent += static_cast<size_t>(sent);
  12800. }
  12801. detail::close_socket(cli);
  12802. }
  12803. detail::close_socket(srv);
  12804. });
  12805. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12806. size_t total_read = 0;
  12807. {
  12808. Client cli("127.0.0.1", PORT + 2);
  12809. cli.set_read_timeout(5, 0);
  12810. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12811. auto stream = cli.open_stream("GET", "/malicious");
  12812. ASSERT_TRUE(stream.is_valid());
  12813. char buffer[64 * 1024];
  12814. ssize_t n;
  12815. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12816. total_read += static_cast<size_t>(n);
  12817. }
  12818. } // StreamHandle and Client destroyed here, closing the socket
  12819. server_thread.join();
  12820. // With set_payload_max_length, the client must stop reading before consuming
  12821. // all 10MB. The read loop should be cut off at or near the configured limit.
  12822. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12823. << "Client read " << total_read << " bytes, exceeding the configured "
  12824. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12825. }
  12826. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12827. // the entire response body without truncation.
  12828. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12829. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12830. #ifndef _WIN32
  12831. signal(SIGPIPE, SIG_IGN);
  12832. #endif
  12833. auto server_thread = std::thread([] {
  12834. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12835. default_socket_options(srv);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12837. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12838. sockaddr_in addr{};
  12839. addr.sin_family = AF_INET;
  12840. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12842. int opt = 1;
  12843. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12844. #ifdef _WIN32
  12845. reinterpret_cast<const char *>(&opt),
  12846. #else
  12847. &opt,
  12848. #endif
  12849. sizeof(opt));
  12850. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12851. ::listen(srv, 1);
  12852. sockaddr_in cli_addr{};
  12853. socklen_t cli_len = sizeof(cli_addr);
  12854. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12855. if (cli != INVALID_SOCKET) {
  12856. char buf[4096];
  12857. ::recv(cli, buf, sizeof(buf), 0);
  12858. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12859. "Connection: close\r\n"
  12860. "\r\n";
  12861. ::send(cli,
  12862. #ifdef _WIN32
  12863. static_cast<const char *>(response_header.c_str()),
  12864. static_cast<int>(response_header.size()),
  12865. #else
  12866. response_header.c_str(), response_header.size(),
  12867. #endif
  12868. 0);
  12869. std::string chunk(64 * 1024, 'A');
  12870. size_t total_sent = 0;
  12871. while (total_sent < DATA_SIZE) {
  12872. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12873. auto sent = ::send(cli,
  12874. #ifdef _WIN32
  12875. static_cast<const char *>(chunk.c_str()),
  12876. static_cast<int>(to_send),
  12877. #else
  12878. chunk.c_str(), to_send,
  12879. #endif
  12880. 0);
  12881. if (sent <= 0) break;
  12882. total_sent += static_cast<size_t>(sent);
  12883. }
  12884. #ifdef _WIN32
  12885. ::shutdown(cli, SD_SEND);
  12886. #else
  12887. ::shutdown(cli, SHUT_WR);
  12888. #endif
  12889. // Drain until the client closes its end, ensuring all data is delivered
  12890. char drain[1024];
  12891. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12892. detail::close_socket(cli);
  12893. }
  12894. detail::close_socket(srv);
  12895. });
  12896. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12897. size_t total_read = 0;
  12898. {
  12899. Client cli("127.0.0.1", PORT + 2);
  12900. cli.set_read_timeout(5, 0);
  12901. cli.set_payload_max_length(0); // 0 means no limit
  12902. auto stream = cli.open_stream("GET", "/data");
  12903. ASSERT_TRUE(stream.is_valid());
  12904. char buffer[64 * 1024];
  12905. ssize_t n;
  12906. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12907. total_read += static_cast<size_t>(n);
  12908. }
  12909. }
  12910. server_thread.join();
  12911. EXPECT_EQ(total_read, DATA_SIZE)
  12912. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12913. << " bytes without truncation, but only read " << total_read << " bytes.";
  12914. }
  12915. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12916. // enormous Content-Length must not cause the client to pre-allocate a huge
  12917. // response body buffer. The reservation is capped at payload_max_length_, and
  12918. // the read itself fails when the body exceeds the limit.
  12919. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12920. #ifndef _WIN32
  12921. signal(SIGPIPE, SIG_IGN);
  12922. #endif
  12923. auto server_thread = std::thread([] {
  12924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12925. default_socket_options(srv);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12927. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12928. sockaddr_in addr{};
  12929. addr.sin_family = AF_INET;
  12930. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12931. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12932. int opt = 1;
  12933. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12934. #ifdef _WIN32
  12935. reinterpret_cast<const char *>(&opt),
  12936. #else
  12937. &opt,
  12938. #endif
  12939. sizeof(opt));
  12940. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12941. ::listen(srv, 1);
  12942. sockaddr_in cli_addr{};
  12943. socklen_t cli_len = sizeof(cli_addr);
  12944. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12945. if (cli != INVALID_SOCKET) {
  12946. char buf[4096];
  12947. ::recv(cli, buf, sizeof(buf), 0);
  12948. // Malicious response: claim a 20GB body but send only a tiny payload.
  12949. std::string response = "HTTP/1.1 200 OK\r\n"
  12950. "Content-Length: 20000000000\r\n"
  12951. "\r\n"
  12952. "abc";
  12953. ::send(cli,
  12954. #ifdef _WIN32
  12955. static_cast<const char *>(response.c_str()),
  12956. static_cast<int>(response.size()),
  12957. #else
  12958. response.c_str(), response.size(),
  12959. #endif
  12960. 0);
  12961. detail::close_socket(cli);
  12962. }
  12963. detail::close_socket(srv);
  12964. });
  12965. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12966. {
  12967. Client cli("127.0.0.1", PORT + 2);
  12968. cli.set_read_timeout(5, 0);
  12969. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12970. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12971. // (server claims more bytes than payload_max_length permits), but it must
  12972. // not exhaust memory before getting there.
  12973. auto res = cli.Get("/malicious");
  12974. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12975. }
  12976. server_thread.join();
  12977. }
  12978. // Verify that content_receiver bypasses the default payload_max_length,
  12979. // allowing streaming downloads larger than 100MB without requiring an explicit
  12980. // set_payload_max_length call.
  12981. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12982. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12983. #ifndef _WIN32
  12984. signal(SIGPIPE, SIG_IGN);
  12985. #endif
  12986. auto server_thread = std::thread([] {
  12987. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12988. default_socket_options(srv);
  12989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12991. sockaddr_in addr{};
  12992. addr.sin_family = AF_INET;
  12993. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12994. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12995. int opt = 1;
  12996. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12997. #ifdef _WIN32
  12998. reinterpret_cast<const char *>(&opt),
  12999. #else
  13000. &opt,
  13001. #endif
  13002. sizeof(opt));
  13003. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13004. ::listen(srv, 1);
  13005. sockaddr_in cli_addr{};
  13006. socklen_t cli_len = sizeof(cli_addr);
  13007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13008. if (cli != INVALID_SOCKET) {
  13009. char buf[4096];
  13010. ::recv(cli, buf, sizeof(buf), 0);
  13011. // Response with Content-Length larger than default 100MB limit
  13012. auto content_length = std::to_string(DATA_SIZE);
  13013. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13014. "Content-Length: " +
  13015. content_length +
  13016. "\r\n"
  13017. "Connection: close\r\n"
  13018. "\r\n";
  13019. ::send(cli,
  13020. #ifdef _WIN32
  13021. static_cast<const char *>(response_header.c_str()),
  13022. static_cast<int>(response_header.size()),
  13023. #else
  13024. response_header.c_str(), response_header.size(),
  13025. #endif
  13026. 0);
  13027. std::string chunk(64 * 1024, 'A');
  13028. size_t total_sent = 0;
  13029. while (total_sent < DATA_SIZE) {
  13030. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13031. auto sent = ::send(cli,
  13032. #ifdef _WIN32
  13033. static_cast<const char *>(chunk.c_str()),
  13034. static_cast<int>(to_send),
  13035. #else
  13036. chunk.c_str(), to_send,
  13037. #endif
  13038. 0);
  13039. if (sent <= 0) break;
  13040. total_sent += static_cast<size_t>(sent);
  13041. }
  13042. detail::close_socket(cli);
  13043. }
  13044. detail::close_socket(srv);
  13045. });
  13046. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13047. size_t total_received = 0;
  13048. {
  13049. Client cli("127.0.0.1", PORT + 2);
  13050. cli.set_read_timeout(10, 0);
  13051. // Do NOT call set_payload_max_length — use the default 100MB limit
  13052. auto res =
  13053. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13054. total_received += data_length;
  13055. return true;
  13056. });
  13057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13058. EXPECT_EQ(StatusCode::OK_200, res->status);
  13059. }
  13060. server_thread.join();
  13061. EXPECT_EQ(total_received, DATA_SIZE)
  13062. << "With content_receiver, the client should read all " << DATA_SIZE
  13063. << " bytes despite the default 100MB payload_max_length, but only read "
  13064. << total_received << " bytes.";
  13065. }
  13066. // Verify that an explicit set_payload_max_length smaller than the response is
  13067. // enforced even when a content_receiver is used.
  13068. TEST(ClientVulnerabilityTest,
  13069. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13070. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13071. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13072. #ifndef _WIN32
  13073. signal(SIGPIPE, SIG_IGN);
  13074. #endif
  13075. auto server_thread = std::thread([] {
  13076. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13077. default_socket_options(srv);
  13078. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13079. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13080. sockaddr_in addr{};
  13081. addr.sin_family = AF_INET;
  13082. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13083. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13084. int opt = 1;
  13085. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13086. #ifdef _WIN32
  13087. reinterpret_cast<const char *>(&opt),
  13088. #else
  13089. &opt,
  13090. #endif
  13091. sizeof(opt));
  13092. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13093. ::listen(srv, 1);
  13094. sockaddr_in cli_addr{};
  13095. socklen_t cli_len = sizeof(cli_addr);
  13096. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13097. if (cli != INVALID_SOCKET) {
  13098. char buf[4096];
  13099. ::recv(cli, buf, sizeof(buf), 0);
  13100. auto content_length = std::to_string(DATA_SIZE);
  13101. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13102. "Content-Length: " +
  13103. content_length +
  13104. "\r\n"
  13105. "Connection: close\r\n"
  13106. "\r\n";
  13107. ::send(cli,
  13108. #ifdef _WIN32
  13109. static_cast<const char *>(response_header.c_str()),
  13110. static_cast<int>(response_header.size()),
  13111. #else
  13112. response_header.c_str(), response_header.size(),
  13113. #endif
  13114. 0);
  13115. std::string chunk(64 * 1024, 'A');
  13116. size_t total_sent = 0;
  13117. while (total_sent < DATA_SIZE) {
  13118. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13119. auto sent = ::send(cli,
  13120. #ifdef _WIN32
  13121. static_cast<const char *>(chunk.c_str()),
  13122. static_cast<int>(to_send),
  13123. #else
  13124. chunk.c_str(), to_send,
  13125. #endif
  13126. 0);
  13127. if (sent <= 0) break;
  13128. total_sent += static_cast<size_t>(sent);
  13129. }
  13130. detail::close_socket(cli);
  13131. }
  13132. detail::close_socket(srv);
  13133. });
  13134. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13135. size_t total_received = 0;
  13136. {
  13137. Client cli("127.0.0.1", PORT + 2);
  13138. cli.set_read_timeout(10, 0);
  13139. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13140. auto res =
  13141. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13142. total_received += data_length;
  13143. return true;
  13144. });
  13145. // Should fail because 200MB exceeds the explicit 150MB limit
  13146. EXPECT_FALSE(res);
  13147. }
  13148. server_thread.join();
  13149. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13150. << "Client with content_receiver should respect the explicit "
  13151. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13152. << total_received << " bytes.";
  13153. }
  13154. // Verify that an explicit set_payload_max_length larger than the response
  13155. // allows the content_receiver to read all data successfully.
  13156. TEST(ClientVulnerabilityTest,
  13157. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13158. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13159. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13160. #ifndef _WIN32
  13161. signal(SIGPIPE, SIG_IGN);
  13162. #endif
  13163. auto server_thread = std::thread([] {
  13164. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13165. default_socket_options(srv);
  13166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13167. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13168. sockaddr_in addr{};
  13169. addr.sin_family = AF_INET;
  13170. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13171. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13172. int opt = 1;
  13173. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13174. #ifdef _WIN32
  13175. reinterpret_cast<const char *>(&opt),
  13176. #else
  13177. &opt,
  13178. #endif
  13179. sizeof(opt));
  13180. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13181. ::listen(srv, 1);
  13182. sockaddr_in cli_addr{};
  13183. socklen_t cli_len = sizeof(cli_addr);
  13184. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13185. if (cli != INVALID_SOCKET) {
  13186. char buf[4096];
  13187. ::recv(cli, buf, sizeof(buf), 0);
  13188. auto content_length = std::to_string(DATA_SIZE);
  13189. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13190. "Content-Length: " +
  13191. content_length +
  13192. "\r\n"
  13193. "Connection: close\r\n"
  13194. "\r\n";
  13195. ::send(cli,
  13196. #ifdef _WIN32
  13197. static_cast<const char *>(response_header.c_str()),
  13198. static_cast<int>(response_header.size()),
  13199. #else
  13200. response_header.c_str(), response_header.size(),
  13201. #endif
  13202. 0);
  13203. std::string chunk(64 * 1024, 'A');
  13204. size_t total_sent = 0;
  13205. while (total_sent < DATA_SIZE) {
  13206. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13207. auto sent = ::send(cli,
  13208. #ifdef _WIN32
  13209. static_cast<const char *>(chunk.c_str()),
  13210. static_cast<int>(to_send),
  13211. #else
  13212. chunk.c_str(), to_send,
  13213. #endif
  13214. 0);
  13215. if (sent <= 0) break;
  13216. total_sent += static_cast<size_t>(sent);
  13217. }
  13218. #ifdef _WIN32
  13219. ::shutdown(cli, SD_SEND);
  13220. #else
  13221. ::shutdown(cli, SHUT_WR);
  13222. #endif
  13223. char drain[1024];
  13224. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13225. detail::close_socket(cli);
  13226. }
  13227. detail::close_socket(srv);
  13228. });
  13229. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13230. size_t total_received = 0;
  13231. {
  13232. Client cli("127.0.0.1", PORT + 2);
  13233. cli.set_read_timeout(10, 0);
  13234. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13235. auto res =
  13236. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13237. total_received += data_length;
  13238. return true;
  13239. });
  13240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13241. EXPECT_EQ(StatusCode::OK_200, res->status);
  13242. }
  13243. server_thread.join();
  13244. EXPECT_EQ(total_received, DATA_SIZE)
  13245. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13246. << " bytes (larger than " << DATA_SIZE
  13247. << " bytes response), content_receiver should read all data, but only "
  13248. "read "
  13249. << total_received << " bytes.";
  13250. }
  13251. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13252. // Regression test for "zip bomb" attack on the client side: a malicious server
  13253. // sends a small gzip-compressed response that decompresses to a huge payload.
  13254. // The client must enforce payload_max_length on the decompressed size.
  13255. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13256. constexpr size_t DECOMPRESSED_SIZE =
  13257. 10 * 1024 * 1024; // 10MB after decompression
  13258. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13259. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13260. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13261. std::string compressed;
  13262. {
  13263. httplib::detail::gzip_compressor compressor;
  13264. bool ok =
  13265. compressor.compress(uncompressed.data(), uncompressed.size(),
  13266. /*last=*/true, [&](const char *buf, size_t len) {
  13267. compressed.append(buf, len);
  13268. return true;
  13269. });
  13270. ASSERT_TRUE(ok);
  13271. }
  13272. // Sanity: compressed data should be much smaller than the decompressed size
  13273. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13274. #ifndef _WIN32
  13275. signal(SIGPIPE, SIG_IGN);
  13276. #endif
  13277. // Set up the listening socket in the main thread so the server is guaranteed
  13278. // to be ready before the client connects (eliminates race condition).
  13279. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13280. default_socket_options(srv);
  13281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13282. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13283. sockaddr_in addr{};
  13284. addr.sin_family = AF_INET;
  13285. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13286. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13287. int opt = 1;
  13288. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13289. #ifdef _WIN32
  13290. reinterpret_cast<const char *>(&opt),
  13291. #else
  13292. &opt,
  13293. #endif
  13294. sizeof(opt));
  13295. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13296. ASSERT_EQ(0, ::listen(srv, 1));
  13297. auto server_thread = std::thread([&compressed, srv] {
  13298. sockaddr_in cli_addr{};
  13299. socklen_t cli_len = sizeof(cli_addr);
  13300. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13301. if (cli != INVALID_SOCKET) {
  13302. // Read the full HTTP request (until \r\n\r\n)
  13303. char buf[4096];
  13304. size_t total = 0;
  13305. while (total < sizeof(buf)) {
  13306. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13307. if (n <= 0) break;
  13308. total += static_cast<size_t>(n);
  13309. // Check for end of headers
  13310. if (total >= 4) {
  13311. std::string req(buf, total);
  13312. if (req.find("\r\n\r\n") != std::string::npos) break;
  13313. }
  13314. }
  13315. // Malicious response: gzip-compressed body, no Content-Length
  13316. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13317. "Content-Encoding: gzip\r\n"
  13318. "Connection: close\r\n"
  13319. "\r\n";
  13320. ::send(cli,
  13321. #ifdef _WIN32
  13322. static_cast<const char *>(response_header.c_str()),
  13323. static_cast<int>(response_header.size()),
  13324. #else
  13325. response_header.c_str(), response_header.size(),
  13326. #endif
  13327. 0);
  13328. // Send the compressed payload (small on the wire, huge when decompressed)
  13329. size_t total_sent = 0;
  13330. while (total_sent < compressed.size()) {
  13331. auto to_send = std::min(compressed.size() - total_sent,
  13332. static_cast<size_t>(64 * 1024));
  13333. auto sent =
  13334. ::send(cli,
  13335. #ifdef _WIN32
  13336. static_cast<const char *>(compressed.c_str() + total_sent),
  13337. static_cast<int>(to_send),
  13338. #else
  13339. compressed.c_str() + total_sent, to_send,
  13340. #endif
  13341. 0);
  13342. if (sent <= 0) break;
  13343. total_sent += static_cast<size_t>(sent);
  13344. }
  13345. detail::close_socket(cli);
  13346. }
  13347. });
  13348. auto se = detail::scope_exit([&] {
  13349. detail::close_socket(srv);
  13350. server_thread.join();
  13351. });
  13352. size_t total_decompressed = 0;
  13353. {
  13354. Client cli("127.0.0.1", PORT + 3);
  13355. cli.set_read_timeout(5, 0);
  13356. cli.set_decompress(true);
  13357. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13358. auto stream = cli.open_stream("GET", "/zipbomb");
  13359. ASSERT_TRUE(stream.is_valid());
  13360. char buffer[64 * 1024];
  13361. ssize_t n;
  13362. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13363. total_decompressed += static_cast<size_t>(n);
  13364. }
  13365. }
  13366. // The decompressed size must be capped by payload_max_length. Without
  13367. // protection, the client would decompress the full 10MB from a tiny
  13368. // compressed payload, enabling a zip bomb DoS attack.
  13369. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13370. << "Client decompressed " << total_decompressed
  13371. << " bytes from a gzip response. The decompressed size should be "
  13372. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13373. }
  13374. #endif
  13375. TEST(HostAndPortPropertiesTest, NoSSL) {
  13376. httplib::Client cli("www.google.com", 1234);
  13377. ASSERT_EQ("www.google.com", cli.host());
  13378. ASSERT_EQ(1234, cli.port());
  13379. }
  13380. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13381. httplib::Client cli("www.google.com:1234");
  13382. ASSERT_EQ("www.google.com", cli.host());
  13383. ASSERT_EQ(1234, cli.port());
  13384. }
  13385. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13386. // Port number that overflows int — should not crash, client becomes invalid
  13387. httplib::Client cli("http://www.google.com:99999999999999999999");
  13388. ASSERT_FALSE(cli.is_valid());
  13389. }
  13390. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13391. // Port 99999 exceeds valid range (1-65535) — should not crash
  13392. httplib::Client cli("http://www.google.com:99999");
  13393. ASSERT_FALSE(cli.is_valid());
  13394. auto res = cli.Get("/");
  13395. EXPECT_FALSE(res);
  13396. EXPECT_EQ(Error::Connection, res.error());
  13397. }
  13398. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13399. httplib::Client cli("http://user:pass@localhost:1234");
  13400. ASSERT_FALSE(cli.is_valid());
  13401. EXPECT_FALSE(cli.Get("/"));
  13402. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13403. }
  13404. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13405. httplib::Client cli("http://www.google.com:80abc");
  13406. ASSERT_FALSE(cli.is_valid());
  13407. }
  13408. #ifdef CPPHTTPLIB_SSL_ENABLED
  13409. TEST(HostAndPortPropertiesTest, SSL) {
  13410. httplib::SSLClient cli("www.google.com");
  13411. ASSERT_EQ("www.google.com", cli.host());
  13412. ASSERT_EQ(443, cli.port());
  13413. }
  13414. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13415. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13416. std::string cert;
  13417. read_file(CA_CERT_FILE, cert);
  13418. httplib::SSLClient httplib_client("www.google.com");
  13419. // Load CA store first time
  13420. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13421. // Load CA store second time (update)
  13422. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13423. // Verify client is still valid and can make connections
  13424. httplib_client.enable_server_certificate_verification(true);
  13425. auto res = httplib_client.Get("/");
  13426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13427. // Google may return 200 or 301 depending on various factors
  13428. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13429. res->status == StatusCode::MovedPermanently_301);
  13430. }
  13431. TEST(SSLClientTest, ServerNameIndication_Online) {
  13432. auto host = "httpbingo.org";
  13433. auto path = std::string{"/get"};
  13434. SSLClient cli(host, 443);
  13435. auto res = cli.Get(path);
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. ASSERT_EQ(StatusCode::OK_200, res->status);
  13438. }
  13439. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13440. // Use a site that will cause SSL verification failure due to self-signed cert
  13441. SSLClient cli("self-signed.badssl.com", 443);
  13442. cli.enable_server_certificate_verification(true);
  13443. auto res = cli.Get("/");
  13444. ASSERT_TRUE(!res);
  13445. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13446. // Verify backend error is captured for SSLServerVerification
  13447. // This occurs when certificate verification fails
  13448. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13449. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13450. EXPECT_NE(0UL, res.ssl_backend_error());
  13451. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13452. res.ssl_error());
  13453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13454. #if !defined(_WIN32) || \
  13455. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13456. // On non-Windows or when Windows Schannel is disabled, the error comes
  13457. // from OpenSSL's verification
  13458. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13459. res.ssl_backend_error());
  13460. #endif
  13461. #endif
  13462. }
  13463. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13464. // Use a site where hostname doesn't match the certificate
  13465. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13466. SSLClient cli("wrong.host.badssl.com", 443);
  13467. cli.enable_server_certificate_verification(true);
  13468. cli.enable_server_hostname_verification(true);
  13469. auto res = cli.Get("/");
  13470. ASSERT_TRUE(!res);
  13471. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13472. // Verify backend error is captured for hostname verification failure
  13473. EXPECT_NE(0UL, res.ssl_backend_error());
  13474. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13475. res.ssl_error());
  13476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13477. #if !defined(_WIN32) || \
  13478. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13479. // On non-Windows or when Windows Schannel is disabled, the error comes
  13480. // from OpenSSL's hostname verification
  13481. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13482. res.ssl_backend_error());
  13483. #endif
  13484. #endif
  13485. }
  13486. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13487. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13488. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13489. SSLClient cli("www.google.com", 443);
  13490. cli.enable_server_certificate_verification(true);
  13491. auto res = cli.Get("/");
  13492. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13493. }
  13494. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13495. SSLClient cli("www.google.com", 443);
  13496. cli.enable_server_certificate_verification(true);
  13497. cli.enable_windows_certificate_verification(false);
  13498. auto res = cli.Get("/");
  13499. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13500. }
  13501. // The server sends an intermediate cross-signed by a root Windows trusts,
  13502. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13503. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13504. SSLClient cli("accounts.spotify.com", 443);
  13505. auto res = cli.Get("/");
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13507. << " ssl_backend_error=" << res.ssl_backend_error();
  13508. }
  13509. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13510. // policy status, which no backend reports for a self-signed certificate.
  13511. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13512. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13513. ASSERT_TRUE(svr.is_valid());
  13514. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13515. auto se = detail::scope_exit([&] {
  13516. svr.stop();
  13517. t.join();
  13518. ASSERT_FALSE(svr.is_running());
  13519. });
  13520. svr.wait_until_ready();
  13521. SSLClient cli("127.0.0.1", PORT);
  13522. cli.set_connection_timeout(30);
  13523. auto res = cli.Get("/");
  13524. ASSERT_FALSE(res);
  13525. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13526. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13527. }
  13528. #endif
  13529. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13530. Client cli("https://google.com");
  13531. auto res = cli.Get("/");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13534. }
  13535. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13536. SSLClient cli("google.com");
  13537. cli.set_ca_cert_path(CA_CERT_FILE);
  13538. 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, ServerCertificateVerification3_Online) {
  13543. SSLClient cli("google.com");
  13544. cli.enable_server_certificate_verification(true);
  13545. cli.set_ca_cert_path("hello");
  13546. auto res = cli.Get("/");
  13547. ASSERT_TRUE(!res);
  13548. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13549. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13550. // should be set
  13551. EXPECT_EQ(0, res.ssl_error());
  13552. // Verify backend error is captured for SSLLoadingCerts
  13553. // This error occurs when loading CA certificates fails
  13554. EXPECT_NE(0UL, res.ssl_backend_error());
  13555. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13556. // OpenSSL specific error codes:
  13557. // > openssl errstr 0x80000002
  13558. // error:80000002:system library::No such file or directory
  13559. // > openssl errstr 0xA000126
  13560. // error:0A000126:SSL routines::unexpected eof while reading
  13561. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13562. res.ssl_backend_error() == 0xA000126);
  13563. #endif
  13564. }
  13565. TEST(SSLClientTest, ServerCertificateVerification4) {
  13566. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13567. ASSERT_TRUE(svr.is_valid());
  13568. svr.Get("/test", [&](const Request &, Response &res) {
  13569. res.set_content("test", "text/plain");
  13570. svr.stop();
  13571. ASSERT_TRUE(true);
  13572. });
  13573. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13574. auto se = detail::scope_exit([&] {
  13575. t.join();
  13576. ASSERT_FALSE(svr.is_running());
  13577. });
  13578. svr.wait_until_ready();
  13579. SSLClient cli("127.0.0.1", PORT);
  13580. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13581. cli.enable_server_certificate_verification(true);
  13582. cli.set_connection_timeout(30);
  13583. auto res = cli.Get("/test");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. ASSERT_EQ(StatusCode::OK_200, res->status);
  13586. }
  13587. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13588. std::string cert;
  13589. read_file(CA_CERT_FILE, cert);
  13590. SSLClient cli("google.com");
  13591. cli.load_ca_cert_store(cert.data(), cert.size());
  13592. const auto res = cli.Get("/");
  13593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13594. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13595. }
  13596. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13597. // clang-format off
  13598. static constexpr char cert[] =
  13599. "GlobalSign Root CA\n"
  13600. "==================\n"
  13601. "-----BEGIN CERTIFICATE-----\n"
  13602. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13603. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13604. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13605. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13606. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13607. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13608. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13609. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13610. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13611. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13612. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13613. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13614. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13615. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13616. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13617. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13618. "-----END CERTIFICATE-----\n";
  13619. // clang-format on
  13620. SSLClient cli("google.com");
  13621. cli.load_ca_cert_store(cert, sizeof(cert));
  13622. const auto res = cli.Get("/");
  13623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13624. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13625. }
  13626. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13627. SSLClient cli("www.youtube.com");
  13628. cli.set_ca_cert_path(CA_CERT_FILE);
  13629. cli.enable_server_certificate_verification(true);
  13630. cli.set_follow_location(true);
  13631. auto res = cli.Get("/");
  13632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13633. ASSERT_EQ(StatusCode::OK_200, res->status);
  13634. }
  13635. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13636. SSLClient cli("wWw.YouTube.Com");
  13637. cli.set_ca_cert_path(CA_CERT_FILE);
  13638. cli.enable_server_certificate_verification(true);
  13639. cli.enable_server_hostname_verification(true);
  13640. cli.set_follow_location(true);
  13641. auto res = cli.Get("/");
  13642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13643. ASSERT_EQ(StatusCode::OK_200, res->status);
  13644. }
  13645. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13646. SSLClient cli("gOoGlE.COm");
  13647. cli.enable_server_certificate_verification(true);
  13648. cli.enable_server_hostname_verification(true);
  13649. cli.set_follow_location(true);
  13650. auto res = cli.Get("/");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. TEST(SSLClientTest, Issue2004_Online) {
  13655. Client client("https://google.com");
  13656. client.set_follow_location(true);
  13657. auto res = client.Get("/");
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. ASSERT_EQ(StatusCode::OK_200, res->status);
  13660. auto body = res->body;
  13661. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13662. }
  13663. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13664. // Create SSLClient with invalid cert/key to make is_valid() return false
  13665. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13666. "nonexistent_key.pem");
  13667. // is_valid() should be false due to cert loading failure
  13668. ASSERT_FALSE(cli.is_valid());
  13669. auto res = cli.Get("/");
  13670. ASSERT_FALSE(res);
  13671. EXPECT_EQ(Error::SSLConnection, res.error());
  13672. }
  13673. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13674. // Test for Issue #2251: SSL error not properly reported when client cert
  13675. // and key paths are swapped or mismatched
  13676. // This simulates the scenario where user accidentally swaps the cert and key
  13677. // files
  13678. // Using client cert file as private key and vice versa (completely wrong)
  13679. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13680. // Should fail validation due to cert/key mismatch
  13681. ASSERT_FALSE(cli.is_valid());
  13682. // Attempt to make a request should fail with proper error
  13683. auto res = cli.Get("/");
  13684. ASSERT_FALSE(res);
  13685. EXPECT_EQ(Error::SSLConnection, res.error());
  13686. // SSL error should be recorded in the Result object (this is the key fix for
  13687. // Issue #2251)
  13688. auto backend_error = res.ssl_backend_error();
  13689. EXPECT_NE(0u, backend_error);
  13690. }
  13691. // Tests cert/key mismatch detection at the TLS context level
  13692. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13693. // Test that using mismatched cert/key causes connection failure.
  13694. // We verify this at the SSLClient level rather than through internal
  13695. // TLS API functions.
  13696. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13697. cli.enable_server_certificate_verification(false);
  13698. cli.set_connection_timeout(2);
  13699. // The mismatch should cause a connection or handshake error
  13700. auto res = cli.Get("/test");
  13701. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13702. // Either way, the request should fail
  13703. EXPECT_FALSE(res);
  13704. }
  13705. #endif
  13706. #if 0
  13707. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13708. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13709. ASSERT_TRUE(cli != nullptr);
  13710. cli->set_address_family(AF_INET6);
  13711. cli->set_interface("en0");
  13712. auto res = cli->Get("/get");
  13713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13714. ASSERT_EQ(StatusCode::OK_200, res->status);
  13715. }
  13716. #endif
  13717. // Client certificate tests - work with all TLS backends
  13718. #ifdef CPPHTTPLIB_SSL_ENABLED
  13719. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13720. void ClientCertPresent(
  13721. const std::string &client_cert_file,
  13722. const std::string &client_private_key_file,
  13723. const std::string &client_encrypted_private_key_pass = std::string(),
  13724. const ClientCertServerSetup &setup = nullptr) {
  13725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13726. ASSERT_TRUE(svr.is_valid());
  13727. if (setup) { setup(svr); }
  13728. svr.Get("/test", [&](const Request &req, Response &res) {
  13729. res.set_content("test", "text/plain");
  13730. auto cert = req.peer_cert();
  13731. ASSERT_TRUE(static_cast<bool>(cert));
  13732. std::string common_name = cert.subject_cn();
  13733. EXPECT_EQ("Common Name", common_name);
  13734. });
  13735. auto port = svr.bind_to_any_port(HOST);
  13736. ASSERT_LT(0, port);
  13737. thread t = thread([&]() { svr.listen_after_bind(); });
  13738. auto se = detail::scope_exit([&] {
  13739. svr.stop();
  13740. t.join();
  13741. ASSERT_FALSE(svr.is_running());
  13742. });
  13743. svr.wait_until_ready();
  13744. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13745. client_encrypted_private_key_pass);
  13746. cli.enable_server_certificate_verification(false);
  13747. cli.set_connection_timeout(30);
  13748. auto res = cli.Get("/test");
  13749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13750. ASSERT_EQ(StatusCode::OK_200, res->status);
  13751. }
  13752. TEST(SSLClientServerTest, ClientCertPresent) {
  13753. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13754. }
  13755. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13756. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13757. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13758. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13759. }
  13760. // Expects svr, which must require client certificates, to reject a client
  13761. // that has none
  13762. void RejectsClientWithoutCert(SSLServer &svr) {
  13763. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13764. auto port = svr.bind_to_any_port(HOST);
  13765. ASSERT_LT(0, port);
  13766. thread t = thread([&]() { svr.listen_after_bind(); });
  13767. auto se = detail::scope_exit([&] {
  13768. svr.stop();
  13769. t.join();
  13770. ASSERT_FALSE(svr.is_running());
  13771. });
  13772. svr.wait_until_ready();
  13773. SSLClient cli(HOST, port);
  13774. cli.set_connection_timeout(30);
  13775. // Skip the server certificate check, so that the request fails because the
  13776. // client certificate is missing rather than because cert.pem is not trusted
  13777. cli.enable_server_certificate_verification(false);
  13778. auto res = cli.Get("/test");
  13779. ASSERT_FALSE(res);
  13780. // The server rejects the client during the handshake, or on TLS 1.3 right
  13781. // after it, which the client notices on its first write or read
  13782. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13783. res.error() == Error::Write || res.error() == Error::Read)
  13784. << to_string(res.error());
  13785. if (res.error() == Error::SSLConnection) {
  13786. EXPECT_NE(0UL, res.ssl_backend_error());
  13787. }
  13788. // A rejection noticed on the write keeps the TLS error the write hit
  13789. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13790. }
  13791. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13793. ASSERT_TRUE(svr.is_valid());
  13794. if (setup) { setup(svr); }
  13795. RejectsClientWithoutCert(svr);
  13796. }
  13797. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13798. // A server that requires client certificates must keep requiring them after
  13799. // setup changes it, and keep accepting a client that has one
  13800. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13801. ClientCertMissing(setup);
  13802. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13803. setup);
  13804. }
  13805. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13806. ClientCertStillRequired([](SSLServer &svr) {
  13807. ASSERT_TRUE(tls::set_verify_callback(
  13808. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13809. });
  13810. }
  13811. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13812. ClientCertStillRequired([](SSLServer &svr) {
  13813. ASSERT_TRUE(tls::set_verify_callback(
  13814. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13815. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13816. });
  13817. }
  13818. // The client verifies the server certificate during the handshake, so a
  13819. // server that fails the check never gets the client certificate, even when a
  13820. // verifier of the client's own accepts it
  13821. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13822. struct Case {
  13823. const char *trusted_ca;
  13824. const char *host;
  13825. Error error;
  13826. };
  13827. // cert2.pem names localhost: the first client does not trust it, and the
  13828. // second trusts it but asks for another name
  13829. for (const auto &c :
  13830. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13831. Case{SERVER_CERT2_FILE, "example.com",
  13832. Error::SSLServerHostnameVerification}}) {
  13833. for (auto with_verifier : {false, true}) {
  13834. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13835. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13836. CLIENT_CA_CERT_FILE);
  13837. ASSERT_TRUE(svr.is_valid());
  13838. std::atomic<bool> got_client_cert{false};
  13839. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13840. [&](const tls::VerifyContext &) {
  13841. got_client_cert = true;
  13842. return true;
  13843. }));
  13844. auto port = svr.bind_to_any_port("127.0.0.1");
  13845. ASSERT_LT(0, port);
  13846. thread t = thread([&] { svr.listen_after_bind(); });
  13847. svr.wait_until_ready();
  13848. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13849. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13850. cli.set_ca_cert_path(c.trusted_ca);
  13851. if (with_verifier) {
  13852. cli.set_server_certificate_verifier(
  13853. [](const tls::VerifyContext &) { return true; });
  13854. }
  13855. auto res = cli.Get("/");
  13856. EXPECT_FALSE(res);
  13857. EXPECT_EQ(c.error, res.error());
  13858. svr.stop();
  13859. t.join();
  13860. EXPECT_FALSE(got_client_cert);
  13861. }
  13862. }
  13863. }
  13864. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13865. std::string cert_pem, key_pem, ca_pem;
  13866. read_file(SERVER_CERT_FILE, cert_pem);
  13867. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13868. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13869. ASSERT_TRUE(
  13870. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13871. }
  13872. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13874. ASSERT_TRUE(svr.is_valid());
  13875. UpdateCertsPemWithClientCA(svr);
  13876. RejectsClientWithoutCert(svr);
  13877. }
  13878. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13879. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13880. }
  13881. // A TLS error from one request must not show up in a later request's Result
  13882. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13884. ASSERT_TRUE(svr.is_valid());
  13885. svr.Get("/test", [](const Request &, Response &res) {
  13886. res.set_content("test", "text/plain");
  13887. });
  13888. auto port = svr.bind_to_any_port(HOST);
  13889. ASSERT_LT(0, port);
  13890. thread t = thread([&]() { svr.listen_after_bind(); });
  13891. auto se = detail::scope_exit([&] {
  13892. svr.stop();
  13893. t.join();
  13894. ASSERT_FALSE(svr.is_running());
  13895. });
  13896. svr.wait_until_ready();
  13897. SSLClient cli(HOST, port);
  13898. cli.set_connection_timeout(30);
  13899. cli.enable_server_hostname_verification(false);
  13900. // cert.pem is not trusted, so the handshake fails
  13901. ASSERT_FALSE(cli.Get("/test"));
  13902. cli.enable_server_certificate_verification(false);
  13903. auto res = cli.Get("/test");
  13904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13905. EXPECT_EQ(0, res.ssl_error());
  13906. EXPECT_EQ(0UL, res.ssl_backend_error());
  13907. }
  13908. // PEM memory-based constructor tests (works with all TLS backends).
  13909. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13910. // terminator after it.
  13911. void PemMemoryClientCertPresent(
  13912. const std::string &client_cert_file,
  13913. const std::string &client_private_key_file,
  13914. const std::string &client_encrypted_private_key_pass = std::string(),
  13915. bool exact_size = false) {
  13916. // Read PEM files into memory
  13917. std::string server_cert_pem, server_key_pem;
  13918. std::string client_ca_pem;
  13919. std::string client_cert_pem, client_key_pem;
  13920. read_file(SERVER_CERT_FILE, server_cert_pem);
  13921. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13922. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13923. read_file(client_cert_file, client_cert_pem);
  13924. read_file(client_private_key_file, client_key_pem);
  13925. std::list<std::vector<char>> exact_copies;
  13926. auto data = [&](const std::string &pem) -> const char * {
  13927. if (!exact_size) { return pem.c_str(); }
  13928. exact_copies.emplace_back(pem.begin(), pem.end());
  13929. return exact_copies.back().data();
  13930. };
  13931. // Create server with PEM memory
  13932. SSLServer::PemMemory server_pem = {
  13933. data(server_cert_pem),
  13934. server_cert_pem.size(),
  13935. data(server_key_pem),
  13936. server_key_pem.size(),
  13937. data(client_ca_pem),
  13938. client_ca_pem.size(),
  13939. nullptr // no password for server key
  13940. };
  13941. SSLServer svr(server_pem);
  13942. ASSERT_TRUE(svr.is_valid());
  13943. svr.Get("/test", [&](const Request &req, Response &res) {
  13944. res.set_content("test", "text/plain");
  13945. auto cert = req.peer_cert();
  13946. ASSERT_TRUE(static_cast<bool>(cert));
  13947. EXPECT_EQ("Common Name", cert.subject_cn());
  13948. });
  13949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13950. auto se = detail::scope_exit([&] {
  13951. svr.stop();
  13952. t.join();
  13953. ASSERT_FALSE(svr.is_running());
  13954. });
  13955. svr.wait_until_ready();
  13956. // Create client with PEM memory
  13957. const char *password = client_encrypted_private_key_pass.empty()
  13958. ? nullptr
  13959. : client_encrypted_private_key_pass.c_str();
  13960. SSLClient::PemMemory client_pem = {
  13961. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13962. client_key_pem.size(), password};
  13963. SSLClient cli(HOST, PORT, client_pem);
  13964. cli.enable_server_certificate_verification(false);
  13965. cli.set_connection_timeout(30);
  13966. auto res = cli.Get("/test");
  13967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13968. ASSERT_EQ(StatusCode::OK_200, res->status);
  13969. }
  13970. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13971. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13972. }
  13973. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13974. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13975. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13976. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13977. }
  13978. // A server built from PEM memory with a client CA requires client certificates,
  13979. // also when the CA is a NUL-terminated string passed with a length of 0
  13980. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13981. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13982. read_file(SERVER_CERT_FILE, server_cert_pem);
  13983. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13984. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13985. SSLServer::PemMemory server_pem = {
  13986. server_cert_pem.c_str(),
  13987. server_cert_pem.size(),
  13988. server_key_pem.c_str(),
  13989. server_key_pem.size(),
  13990. client_ca_pem.c_str(),
  13991. client_ca_pem.size(),
  13992. nullptr // no password for server key
  13993. };
  13994. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13995. SCOPED_TRACE(client_ca_pem_len);
  13996. server_pem.client_ca_pem_len = client_ca_pem_len;
  13997. SSLServer svr(server_pem);
  13998. ASSERT_TRUE(svr.is_valid());
  13999. RejectsClientWithoutCert(svr);
  14000. }
  14001. // An empty CA fails to load instead of turning the check off
  14002. server_pem.client_ca_pem = "";
  14003. server_pem.client_ca_pem_len = 0;
  14004. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14005. }
  14006. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14007. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14008. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14009. true);
  14010. }
  14011. // A length shorter than the PEM cuts it short, so it no longer loads
  14012. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14013. std::string cert, key;
  14014. read_file(SERVER_CERT_FILE, cert);
  14015. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14016. for (auto cut_cert : {true, false}) {
  14017. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14018. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14019. SSLServer::PemMemory server_pem = {
  14020. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14021. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14022. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14023. key_len, nullptr};
  14024. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14025. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14026. key.c_str(), key_len, nullptr};
  14027. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14028. }
  14029. }
  14030. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14031. class NoListenSSLServer : public SSLServer {
  14032. public:
  14033. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14034. const char *client_ca_cert_file_path,
  14035. const char *client_ca_cert_dir_path = nullptr)
  14036. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14037. client_ca_cert_dir_path),
  14038. stop_(false) {}
  14039. std::atomic_bool stop_;
  14040. private:
  14041. bool process_and_close_socket(socket_t /*sock*/) override {
  14042. // Don't create SSL context
  14043. while (!stop_.load()) {
  14044. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14045. }
  14046. return true;
  14047. }
  14048. };
  14049. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14050. CLIENT_CA_CERT_FILE);
  14051. ASSERT_TRUE(svr.is_valid());
  14052. svr.Get("/test", [&](const Request &, Response &res) {
  14053. res.set_content("test", "text/plain");
  14054. });
  14055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14056. auto se = detail::scope_exit([&] {
  14057. svr.stop_ = true;
  14058. svr.stop();
  14059. t.join();
  14060. ASSERT_FALSE(svr.is_running());
  14061. });
  14062. svr.wait_until_ready();
  14063. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14064. cli.enable_server_certificate_verification(false);
  14065. cli.set_connection_timeout(1);
  14066. auto res = cli.Get("/test");
  14067. ASSERT_TRUE(!res);
  14068. EXPECT_EQ(Error::SSLConnection, res.error());
  14069. // Timeout results in WantRead error code (maps to backend-specific value)
  14070. EXPECT_NE(0, res.ssl_error());
  14071. }
  14072. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14073. // Test SSLServer with client certificate verification using the standard
  14074. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14076. CLIENT_CA_CERT_DIR);
  14077. ASSERT_TRUE(svr.is_valid());
  14078. svr.Get("/test", [&](const Request &req, Response &res) {
  14079. res.set_content("test", "text/plain");
  14080. auto cert = req.peer_cert();
  14081. ASSERT_TRUE(static_cast<bool>(cert));
  14082. auto common_name = cert.subject_cn();
  14083. EXPECT_EQ("Common Name", common_name);
  14084. });
  14085. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14086. auto se = detail::scope_exit([&] {
  14087. svr.stop();
  14088. t.join();
  14089. ASSERT_FALSE(svr.is_running());
  14090. });
  14091. svr.wait_until_ready();
  14092. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14093. cli.enable_server_certificate_verification(false);
  14094. cli.set_connection_timeout(30);
  14095. auto res = cli.Get("/test");
  14096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14097. ASSERT_EQ(StatusCode::OK_200, res->status);
  14098. }
  14099. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14100. // Verifies that wildcard matching and exact matching work consistently
  14101. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14102. using namespace httplib::tls;
  14103. // We need a running server to test against
  14104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14105. ASSERT_TRUE(svr.is_valid());
  14106. svr.Get("/test", [](const Request &, Response &res) {
  14107. res.set_content("ok", "text/plain");
  14108. });
  14109. thread t([&]() { svr.listen(HOST, PORT); });
  14110. auto se = detail::scope_exit([&] {
  14111. svr.stop();
  14112. t.join();
  14113. });
  14114. svr.wait_until_ready();
  14115. bool verify_callback_called = false;
  14116. bool verify_result_wrong = false;
  14117. SSLClient cli(HOST, PORT);
  14118. cli.enable_server_certificate_verification(true);
  14119. cli.set_ca_cert_path(CA_CERT_FILE);
  14120. cli.set_connection_timeout(5);
  14121. // Note: Test certificate has CN="Common Name", not "localhost"
  14122. bool verify_result_cn = false;
  14123. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14124. verify_callback_called = true;
  14125. if (!ctx.cert) return false;
  14126. // Test 1: "Common Name" should match (our test server cert CN)
  14127. verify_result_cn = ctx.check_hostname("Common Name");
  14128. // Test 2: wrong hostname should not match
  14129. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14130. return true; // Accept for the purpose of this test
  14131. });
  14132. auto res = cli.Get("/test");
  14133. // The request may succeed or fail depending on cert configuration
  14134. // but the callback should have been called
  14135. ASSERT_TRUE(verify_callback_called)
  14136. << "Verify callback should have been called";
  14137. // CN="Common Name" should match our test certificate
  14138. //
  14139. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14140. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14141. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14142. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14143. // <openssl/base.h>, which is included transitively when
  14144. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14145. #if defined(OPENSSL_IS_BORINGSSL)
  14146. EXPECT_FALSE(verify_result_cn)
  14147. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14148. #else
  14149. EXPECT_TRUE(verify_result_cn)
  14150. << "verify_hostname should match 'Common Name' (certificate CN)";
  14151. #endif
  14152. // Wrong hostname should not match
  14153. EXPECT_FALSE(verify_result_wrong)
  14154. << "verify_hostname should not match 'wronghost.example.com'";
  14155. }
  14156. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14157. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14158. // X509_check_ip behavior and must hold for every backend.
  14159. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14160. using namespace httplib::tls;
  14161. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14162. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14163. ASSERT_TRUE(svr.is_valid());
  14164. svr.Get("/test", [](const Request &, Response &res) {
  14165. res.set_content("ok", "text/plain");
  14166. });
  14167. thread t([&]() { svr.listen(HOST, PORT); });
  14168. auto se = detail::scope_exit([&] {
  14169. svr.stop();
  14170. t.join();
  14171. });
  14172. svr.wait_until_ready();
  14173. bool verify_callback_called = false;
  14174. bool ip_matched_via_cn = true;
  14175. SSLClient cli(HOST, PORT);
  14176. cli.enable_server_certificate_verification(true);
  14177. cli.set_ca_cert_path(CA_CERT_FILE);
  14178. cli.set_connection_timeout(5);
  14179. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14180. verify_callback_called = true;
  14181. if (!ctx.cert) return false;
  14182. // The IP appears only in the CN, so it must NOT be accepted.
  14183. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14184. return true; // Accept for the purpose of this test
  14185. });
  14186. cli.Get("/test");
  14187. ASSERT_TRUE(verify_callback_called)
  14188. << "Verify callback should have been called";
  14189. EXPECT_FALSE(ip_matched_via_cn)
  14190. << "An IP host must not be authenticated via the certificate CN";
  14191. }
  14192. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14193. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14194. using namespace httplib::tls;
  14195. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14196. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14197. ASSERT_TRUE(svr.is_valid());
  14198. svr.Get("/test", [](const Request &, Response &res) {
  14199. res.set_content("ok", "text/plain");
  14200. });
  14201. thread t([&]() { svr.listen(HOST, PORT); });
  14202. auto se = detail::scope_exit([&] {
  14203. svr.stop();
  14204. t.join();
  14205. });
  14206. svr.wait_until_ready();
  14207. bool verify_callback_called = false;
  14208. bool san_matched = false;
  14209. bool wrong_ipv6_matched = true;
  14210. bool cn_ipv6_matched = true;
  14211. SSLClient cli(HOST, PORT);
  14212. cli.enable_server_certificate_verification(true);
  14213. cli.set_ca_cert_path(CA_CERT_FILE);
  14214. cli.set_connection_timeout(5);
  14215. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14216. verify_callback_called = true;
  14217. if (!ctx.cert) return false;
  14218. // Matches the IPv6 iPAddress SAN.
  14219. san_matched = ctx.check_hostname("2001:db8::1");
  14220. // A different IPv6 address must not match.
  14221. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14222. // "::1" lives only in the CN, so it must not be accepted.
  14223. cn_ipv6_matched = ctx.check_hostname("::1");
  14224. return true; // Accept for the purpose of this test
  14225. });
  14226. cli.Get("/test");
  14227. ASSERT_TRUE(verify_callback_called)
  14228. << "Verify callback should have been called";
  14229. EXPECT_TRUE(san_matched)
  14230. << "verify_hostname should match an IPv6 iPAddress SAN";
  14231. EXPECT_FALSE(wrong_ipv6_matched)
  14232. << "verify_hostname should not match a non-matching IPv6 address";
  14233. EXPECT_FALSE(cn_ipv6_matched)
  14234. << "An IPv6 host must not be authenticated via the certificate CN";
  14235. }
  14236. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14237. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14238. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14239. using namespace httplib::tls;
  14240. // SANs: DNS:a.zz, IP:42.46.122.122
  14241. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14242. ASSERT_TRUE(svr.is_valid());
  14243. svr.Get("/test", [](const Request &, Response &res) {
  14244. res.set_content("ok", "text/plain");
  14245. });
  14246. auto port = svr.bind_to_any_port(HOST);
  14247. thread t([&]() { svr.listen_after_bind(); });
  14248. auto se = detail::scope_exit([&] {
  14249. svr.stop();
  14250. t.join();
  14251. });
  14252. svr.wait_until_ready();
  14253. bool verify_callback_called = false;
  14254. bool dns_san_matched = false;
  14255. bool ip_san_matched = false;
  14256. bool ip_matched_via_dns_san = true;
  14257. bool dns_matched_via_ip_san = true;
  14258. bool cn_matched_next_to_dns_san = true;
  14259. SSLClient cli(HOST, port);
  14260. cli.enable_server_certificate_verification(true);
  14261. cli.set_ca_cert_path(CA_CERT_FILE);
  14262. cli.set_connection_timeout(5);
  14263. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14264. verify_callback_called = true;
  14265. if (!ctx.cert) return false;
  14266. dns_san_matched = ctx.check_hostname("a.zz");
  14267. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14268. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14269. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14270. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14271. return true; // Accept for the purpose of this test
  14272. });
  14273. cli.Get("/test");
  14274. ASSERT_TRUE(verify_callback_called)
  14275. << "Verify callback should have been called";
  14276. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14277. EXPECT_TRUE(ip_san_matched)
  14278. << "verify_hostname should match an iPAddress SAN";
  14279. EXPECT_FALSE(ip_matched_via_dns_san)
  14280. << "An IP host must not be authenticated via a dNSName SAN";
  14281. EXPECT_FALSE(dns_matched_via_ip_san)
  14282. << "A DNS host must not be authenticated via an iPAddress SAN";
  14283. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14284. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14285. }
  14286. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14287. // "www.*.example.test" names one host and not every host under example.test.
  14288. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14289. using namespace httplib::tls;
  14290. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14291. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14292. ASSERT_TRUE(svr.is_valid());
  14293. svr.Get("/test", [](const Request &, Response &res) {
  14294. res.set_content("ok", "text/plain");
  14295. });
  14296. auto port = svr.bind_to_any_port(HOST);
  14297. thread t([&]() { svr.listen_after_bind(); });
  14298. auto se = detail::scope_exit([&] {
  14299. svr.stop();
  14300. t.join();
  14301. });
  14302. svr.wait_until_ready();
  14303. bool verify_callback_called = false;
  14304. bool leftmost_wildcard_matched = false;
  14305. bool wildcard_spanned_labels = true;
  14306. bool inner_wildcard_matched = true;
  14307. SSLClient cli(HOST, port);
  14308. cli.enable_server_certificate_verification(true);
  14309. cli.set_ca_cert_path(CA_CERT_FILE);
  14310. cli.set_connection_timeout(5);
  14311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14312. verify_callback_called = true;
  14313. if (!ctx.cert) return false;
  14314. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14315. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14316. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14317. return true; // Accept for the purpose of this test
  14318. });
  14319. cli.Get("/test");
  14320. ASSERT_TRUE(verify_callback_called)
  14321. << "Verify callback should have been called";
  14322. EXPECT_TRUE(leftmost_wildcard_matched)
  14323. << "A leftmost wildcard should match a single label";
  14324. EXPECT_FALSE(wildcard_spanned_labels)
  14325. << "A wildcard label must not match more than one label";
  14326. EXPECT_FALSE(inner_wildcard_matched)
  14327. << "A wildcard outside the leftmost label must not be honoured";
  14328. }
  14329. // sans() must report each SAN entry under its own type.
  14330. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14331. using namespace httplib::tls;
  14332. // SANs: DNS:a.zz, IP:42.46.122.122
  14333. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. svr.Get("/test", [](const Request &, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. auto port = svr.bind_to_any_port(HOST);
  14339. thread t([&]() { svr.listen_after_bind(); });
  14340. auto se = detail::scope_exit([&] {
  14341. svr.stop();
  14342. t.join();
  14343. });
  14344. svr.wait_until_ready();
  14345. bool verify_callback_called = false;
  14346. std::vector<SanEntry> sans;
  14347. SSLClient cli(HOST, port);
  14348. cli.enable_server_certificate_verification(true);
  14349. cli.set_ca_cert_path(CA_CERT_FILE);
  14350. cli.set_connection_timeout(5);
  14351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14352. verify_callback_called = true;
  14353. if (!ctx.cert) return false;
  14354. sans = ctx.sans();
  14355. return true; // Accept for the purpose of this test
  14356. });
  14357. cli.Get("/test");
  14358. ASSERT_TRUE(verify_callback_called)
  14359. << "Verify callback should have been called";
  14360. auto has_san = [&](SanType type, const std::string &value) {
  14361. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14362. return san.type == type && san.value == value;
  14363. });
  14364. };
  14365. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14366. << "sans() should report the dNSName SAN";
  14367. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14368. << "sans() should report the iPAddress SAN";
  14369. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14370. << "sans() must not report the dNSName SAN as an address";
  14371. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14372. << "sans() must not report the iPAddress SAN as a DNS name";
  14373. }
  14374. #endif
  14375. // mbedTLS-specific callback constructor test
  14376. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14377. #ifdef CPPHTTPLIB_SSL_ENABLED
  14378. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14380. ASSERT_TRUE(svr.is_valid());
  14381. // Set up a handler to verify client certificate is present
  14382. bool client_cert_verified = false;
  14383. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14384. // Verify that client certificate was provided
  14385. client_cert_verified = true;
  14386. res.set_content("success", "text/plain");
  14387. });
  14388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14389. auto se = detail::scope_exit([&] {
  14390. svr.stop();
  14391. t.join();
  14392. ASSERT_FALSE(svr.is_running());
  14393. });
  14394. svr.wait_until_ready();
  14395. // Client with certificate
  14396. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14397. cli.enable_server_certificate_verification(false);
  14398. cli.set_connection_timeout(30);
  14399. auto res = cli.Get("/test");
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. ASSERT_EQ(StatusCode::OK_200, res->status);
  14402. ASSERT_TRUE(client_cert_verified);
  14403. EXPECT_EQ("success", res->body);
  14404. }
  14405. #endif
  14406. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14407. // backends
  14408. #ifdef CPPHTTPLIB_SSL_ENABLED
  14409. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14410. using namespace httplib::tls;
  14411. // Test that when client CA cert file is provided,
  14412. // the server properly requests and validates client certificates
  14413. // Create a server with client authentication
  14414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14415. ASSERT_TRUE(svr.is_valid());
  14416. bool handler_called = false;
  14417. svr.Get("/test", [&](const Request &req, Response &res) {
  14418. handler_called = true;
  14419. // Verify that a client certificate was provided
  14420. auto cert = req.peer_cert();
  14421. ASSERT_TRUE(static_cast<bool>(cert));
  14422. // Get the issuer name
  14423. std::string issuer_str = cert.issuer_name();
  14424. ASSERT_FALSE(issuer_str.empty());
  14425. // The client certificate should be issued by our test CA
  14426. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14427. res.set_content("authenticated", "text/plain");
  14428. });
  14429. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. ASSERT_FALSE(svr.is_running());
  14434. });
  14435. svr.wait_until_ready();
  14436. // Connect with a client certificate issued by the CA
  14437. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14438. cli.enable_server_certificate_verification(false);
  14439. cli.set_connection_timeout(30);
  14440. auto res = cli.Get("/test");
  14441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14442. ASSERT_EQ(StatusCode::OK_200, res->status);
  14443. ASSERT_TRUE(handler_called);
  14444. EXPECT_EQ("authenticated", res->body);
  14445. }
  14446. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14447. using namespace httplib::tls;
  14448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14449. ASSERT_TRUE(svr.is_valid());
  14450. svr.Get("/test", [](const Request &, Response &res) {
  14451. res.set_content("ok", "text/plain");
  14452. });
  14453. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14454. auto se = detail::scope_exit([&] {
  14455. svr.stop();
  14456. t.join();
  14457. });
  14458. svr.wait_until_ready();
  14459. SSLClient cli(HOST, PORT);
  14460. cli.enable_server_certificate_verification(false);
  14461. cli.set_connection_timeout(30);
  14462. bool cert_checked = false;
  14463. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14464. if (ctx.cert) {
  14465. auto sans = ctx.sans();
  14466. // Test certificate may or may not have SANs - just verify the API
  14467. // works If SANs exist, verify the types are valid
  14468. for (const auto &san : sans) {
  14469. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14470. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14471. san.type == SanType::OTHER);
  14472. EXPECT_FALSE(san.value.empty());
  14473. }
  14474. cert_checked = true;
  14475. }
  14476. return true;
  14477. });
  14478. auto res = cli.Get("/test");
  14479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14480. EXPECT_TRUE(cert_checked);
  14481. }
  14482. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14483. using namespace httplib::tls;
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. ASSERT_TRUE(svr.is_valid());
  14486. svr.Get("/test", [](const Request &, Response &res) {
  14487. res.set_content("ok", "text/plain");
  14488. });
  14489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. });
  14494. svr.wait_until_ready();
  14495. SSLClient cli(HOST, PORT);
  14496. cli.enable_server_certificate_verification(false);
  14497. cli.set_connection_timeout(30);
  14498. bool validity_checked = false;
  14499. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14500. if (ctx.cert) {
  14501. time_t not_before = 0, not_after = 0;
  14502. bool result = ctx.validity(not_before, not_after);
  14503. EXPECT_TRUE(result);
  14504. // Verify that not_before < now < not_after for a valid cert
  14505. time_t now = time(nullptr);
  14506. EXPECT_LT(not_before, now);
  14507. EXPECT_GT(not_after, now);
  14508. validity_checked = true;
  14509. }
  14510. return true;
  14511. });
  14512. auto res = cli.Get("/test");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. EXPECT_TRUE(validity_checked);
  14515. }
  14516. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14517. using namespace httplib::tls;
  14518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14519. ASSERT_TRUE(svr.is_valid());
  14520. svr.Get("/test", [](const Request &, Response &res) {
  14521. res.set_content("ok", "text/plain");
  14522. });
  14523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14524. auto se = detail::scope_exit([&] {
  14525. svr.stop();
  14526. t.join();
  14527. });
  14528. svr.wait_until_ready();
  14529. SSLClient cli(HOST, PORT);
  14530. cli.enable_server_certificate_verification(false);
  14531. cli.set_connection_timeout(30);
  14532. bool serial_checked = false;
  14533. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14534. if (ctx.cert) {
  14535. std::string serial = ctx.serial();
  14536. EXPECT_FALSE(serial.empty());
  14537. // Serial should be a hex string
  14538. for (char c : serial) {
  14539. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14540. (c >= 'a' && c <= 'f'));
  14541. }
  14542. serial_checked = true;
  14543. }
  14544. return true;
  14545. });
  14546. auto res = cli.Get("/test");
  14547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14548. EXPECT_TRUE(serial_checked);
  14549. }
  14550. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14551. // Test 1: Valid CA file - no error should be recorded
  14552. {
  14553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14554. CLIENT_CA_CERT_FILE);
  14555. ASSERT_TRUE(svr.is_valid());
  14556. // With valid setup, last_ssl_error should be 0
  14557. EXPECT_EQ(0, svr.ssl_last_error());
  14558. }
  14559. // Test 2: Invalid CA file content
  14560. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14561. {
  14562. // Create a temporary file with completely invalid content
  14563. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14564. {
  14565. std::ofstream ofs(temp_invalid_ca);
  14566. ofs << "This is not a certificate file at all\n";
  14567. ofs << "Just plain text content\n";
  14568. }
  14569. // Create server with invalid CA file
  14570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14571. // Clean up temporary file
  14572. std::remove(temp_invalid_ca);
  14573. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14574. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14575. // Note: SSL_CTX_load_verify_locations typically fails first,
  14576. // but our error handling code path is still exercised
  14577. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14578. }
  14579. }
  14580. TEST(VerifyCallbackTest, VerifyContextFields) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14588. auto se = detail::scope_exit([&] {
  14589. svr.stop();
  14590. t.join();
  14591. });
  14592. svr.wait_until_ready();
  14593. SSLClient cli(HOST, PORT);
  14594. cli.enable_server_certificate_verification(false);
  14595. cli.set_connection_timeout(30);
  14596. int callback_count = 0;
  14597. bool saw_leaf_cert = false;
  14598. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14599. if (ctx.cert) {
  14600. callback_count++;
  14601. // We should see at least one certificate (the leaf)
  14602. std::string cn = ctx.subject_cn();
  14603. if (!cn.empty()) { saw_leaf_cert = true; }
  14604. // Verify context fields are populated
  14605. EXPECT_NE(ctx.session, nullptr);
  14606. EXPECT_GE(ctx.depth, 0);
  14607. }
  14608. return true;
  14609. });
  14610. auto res = cli.Get("/test");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. EXPECT_GT(callback_count, 0);
  14613. EXPECT_TRUE(saw_leaf_cert);
  14614. }
  14615. // A verifier that accepts runs alongside the built-in verification, and is the
  14616. // only check once that is turned off.
  14617. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14618. using namespace httplib::tls;
  14619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14620. ASSERT_TRUE(svr.is_valid());
  14621. svr.Get("/test", [](const Request &, Response &res) {
  14622. res.set_content("ok", "text/plain");
  14623. });
  14624. auto port = svr.bind_to_any_port(HOST);
  14625. thread t([&]() { svr.listen_after_bind(); });
  14626. auto se = detail::scope_exit([&] {
  14627. svr.stop();
  14628. t.join();
  14629. });
  14630. svr.wait_until_ready();
  14631. SSLClient cli(HOST, port);
  14632. cli.enable_server_hostname_verification(false);
  14633. auto calls = 0;
  14634. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14635. calls++;
  14636. return true;
  14637. });
  14638. // cert.pem is not trusted
  14639. auto res = cli.Get("/test");
  14640. ASSERT_FALSE(res);
  14641. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14642. EXPECT_GT(calls, 0);
  14643. cli.enable_server_certificate_verification(false);
  14644. res = cli.Get("/test");
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_EQ("ok", res->body);
  14647. }
  14648. // A verifier belongs to the client that set it, not to the thread that set it.
  14649. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14650. using namespace httplib::tls;
  14651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14652. ASSERT_TRUE(svr.is_valid());
  14653. svr.Get("/test", [](const Request &, Response &res) {
  14654. res.set_content("ok", "text/plain");
  14655. });
  14656. auto port = svr.bind_to_any_port(HOST);
  14657. thread t([&]() { svr.listen_after_bind(); });
  14658. auto se = detail::scope_exit([&] {
  14659. svr.stop();
  14660. t.join();
  14661. });
  14662. svr.wait_until_ready();
  14663. auto rejecting_calls = 0;
  14664. SSLClient rejecting(HOST, port);
  14665. rejecting.enable_server_certificate_verification(false);
  14666. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14667. rejecting_calls++;
  14668. return false;
  14669. });
  14670. auto accepting_calls = 0;
  14671. SSLClient accepting(HOST, port);
  14672. accepting.enable_server_certificate_verification(false);
  14673. // Set on another thread than the requests below.
  14674. thread([&]() {
  14675. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14676. accepting_calls++;
  14677. return true;
  14678. });
  14679. }).join();
  14680. // Requested on another thread than the verifier was set on.
  14681. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14682. EXPECT_GT(rejecting_calls, 0);
  14683. auto res = accepting.Get("/test");
  14684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14685. EXPECT_GT(accepting_calls, 0);
  14686. }
  14687. // A verifier replaced while a handshake runs it lives until it returns.
  14688. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14689. using namespace httplib::tls;
  14690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14691. ASSERT_TRUE(svr.is_valid());
  14692. svr.Get("/test", [](const Request &, Response &res) {
  14693. res.set_content("ok", "text/plain");
  14694. });
  14695. auto port = svr.bind_to_any_port(HOST);
  14696. thread t([&]() { svr.listen_after_bind(); });
  14697. auto se = detail::scope_exit([&] {
  14698. svr.stop();
  14699. t.join();
  14700. });
  14701. svr.wait_until_ready();
  14702. SSLClient cli(HOST, port);
  14703. cli.enable_server_certificate_verification(false);
  14704. std::promise<void> entered;
  14705. std::promise<void> replaced;
  14706. auto replaced_future = replaced.get_future();
  14707. auto first_call = true;
  14708. // Long enough to live on the heap
  14709. std::string expected(64, 'v');
  14710. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14711. if (first_call) {
  14712. first_call = false;
  14713. entered.set_value();
  14714. replaced_future.wait();
  14715. }
  14716. return expected == std::string(64, 'v');
  14717. });
  14718. thread request([&]() {
  14719. auto res = cli.Get("/test");
  14720. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14721. });
  14722. entered.get_future().wait();
  14723. cli.set_server_certificate_verifier(
  14724. [](const VerifyContext &) { return true; });
  14725. replaced.set_value();
  14726. request.join();
  14727. }
  14728. // VerifyContext::session is the same handle the other tls:: functions take.
  14729. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14730. using namespace httplib::tls;
  14731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14732. ASSERT_TRUE(svr.is_valid());
  14733. svr.Get("/test", [](const Request &, Response &res) {
  14734. res.set_content("ok", "text/plain");
  14735. });
  14736. auto port = svr.bind_to_any_port(HOST);
  14737. thread t([&]() { svr.listen_after_bind(); });
  14738. auto se = detail::scope_exit([&] {
  14739. svr.stop();
  14740. t.join();
  14741. });
  14742. svr.wait_until_ready();
  14743. SSLClient cli(HOST, port);
  14744. cli.enable_server_certificate_verification(false);
  14745. session_t verifier_session = nullptr;
  14746. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14747. verifier_session = ctx.session;
  14748. return true;
  14749. });
  14750. session_t session_verifier_session = nullptr;
  14751. cli.set_session_verifier([&](session_t session) {
  14752. session_verifier_session = session;
  14753. return SSLVerifierResponse::NoDecisionMade;
  14754. });
  14755. auto res = cli.Get("/test");
  14756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14757. EXPECT_NE(nullptr, verifier_session);
  14758. EXPECT_EQ(session_verifier_session, verifier_session);
  14759. }
  14760. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14761. using httplib::tls::TlsError;
  14762. // Test that verify_error_to_string returns empty for success
  14763. std::string success_str = TlsError::verify_error_to_string(0);
  14764. EXPECT_TRUE(success_str.empty());
  14765. // Test that verify_error_to_string returns non-empty for error codes
  14766. // Using a common error code (certificate expired)
  14767. std::string error_str =
  14768. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14769. EXPECT_FALSE(error_str.empty());
  14770. }
  14771. TEST(SessionVerifierTest, CertificateAccepted) {
  14772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14773. ASSERT_TRUE(svr.is_valid());
  14774. svr.Get("/test", [](const Request &, Response &res) {
  14775. res.set_content("ok", "text/plain");
  14776. });
  14777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14778. auto se = detail::scope_exit([&] {
  14779. svr.stop();
  14780. t.join();
  14781. });
  14782. svr.wait_until_ready();
  14783. SSLClient cli(HOST, PORT);
  14784. cli.enable_server_certificate_verification(false);
  14785. cli.set_connection_timeout(30);
  14786. bool callback_called = false;
  14787. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14788. EXPECT_NE(session, nullptr);
  14789. callback_called = true;
  14790. return SSLVerifierResponse::CertificateAccepted;
  14791. });
  14792. auto res = cli.Get("/test");
  14793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14794. EXPECT_EQ(200, res->status);
  14795. EXPECT_TRUE(callback_called);
  14796. }
  14797. TEST(SessionVerifierTest, CertificateRejected) {
  14798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14799. ASSERT_TRUE(svr.is_valid());
  14800. svr.Get("/test", [](const Request &, Response &res) {
  14801. res.set_content("ok", "text/plain");
  14802. });
  14803. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14804. auto se = detail::scope_exit([&] {
  14805. svr.stop();
  14806. t.join();
  14807. });
  14808. svr.wait_until_ready();
  14809. SSLClient cli(HOST, PORT);
  14810. cli.enable_server_certificate_verification(false);
  14811. cli.set_connection_timeout(30);
  14812. bool callback_called = false;
  14813. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14814. EXPECT_NE(session, nullptr);
  14815. callback_called = true;
  14816. return SSLVerifierResponse::CertificateRejected;
  14817. });
  14818. auto res = cli.Get("/test");
  14819. EXPECT_FALSE(res);
  14820. EXPECT_TRUE(callback_called);
  14821. }
  14822. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14824. ASSERT_TRUE(svr.is_valid());
  14825. svr.Get("/test", [](const Request &, Response &res) {
  14826. res.set_content("ok", "text/plain");
  14827. });
  14828. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14829. auto se = detail::scope_exit([&] {
  14830. svr.stop();
  14831. t.join();
  14832. });
  14833. svr.wait_until_ready();
  14834. // NoDecisionMade with verification disabled should succeed (no default check)
  14835. SSLClient cli(HOST, PORT);
  14836. cli.enable_server_certificate_verification(false);
  14837. cli.set_connection_timeout(30);
  14838. bool callback_called = false;
  14839. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14840. EXPECT_NE(session, nullptr);
  14841. callback_called = true;
  14842. return SSLVerifierResponse::NoDecisionMade;
  14843. });
  14844. auto res = cli.Get("/test");
  14845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14846. EXPECT_EQ(200, res->status);
  14847. EXPECT_TRUE(callback_called);
  14848. }
  14849. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14851. ASSERT_TRUE(svr.is_valid());
  14852. svr.Get("/test", [](const Request &, Response &res) {
  14853. res.set_content("ok", "text/plain");
  14854. });
  14855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14856. auto se = detail::scope_exit([&] {
  14857. svr.stop();
  14858. t.join();
  14859. });
  14860. svr.wait_until_ready();
  14861. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14862. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14863. // so we only check that the request fails, not whether the callback was
  14864. // called.
  14865. SSLClient cli(HOST, PORT);
  14866. cli.enable_server_certificate_verification(true);
  14867. cli.set_connection_timeout(30);
  14868. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14869. EXPECT_NE(session, nullptr);
  14870. return SSLVerifierResponse::NoDecisionMade;
  14871. });
  14872. auto res = cli.Get("/test");
  14873. EXPECT_FALSE(res);
  14874. }
  14875. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14876. // Test SSL server using PemMemory constructor with client CA certificates
  14877. // Read PEM files
  14878. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14879. read_file(SERVER_CERT_FILE, server_cert_pem);
  14880. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14881. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14882. // Create SSLServer with PemMemory constructor including client CA
  14883. SSLServer::PemMemory server_pem = {
  14884. server_cert_pem.c_str(),
  14885. server_cert_pem.size(),
  14886. server_key_pem.c_str(),
  14887. server_key_pem.size(),
  14888. client_ca_pem.c_str(),
  14889. client_ca_pem.size(),
  14890. nullptr // no password for server key
  14891. };
  14892. SSLServer svr(server_pem);
  14893. ASSERT_TRUE(svr.is_valid());
  14894. // No SSL error should be recorded for valid setup
  14895. EXPECT_EQ(0, svr.ssl_last_error());
  14896. // Set up server endpoints
  14897. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. // Start server in a thread
  14901. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14902. svr.wait_until_ready();
  14903. // Connect with client certificate (using constructor with paths)
  14904. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14905. cli.enable_server_certificate_verification(false);
  14906. auto res = cli.Get("/test-pem-ca");
  14907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14908. EXPECT_EQ(200, res->status);
  14909. EXPECT_EQ("ok", res->body);
  14910. svr.stop();
  14911. server_thread.join();
  14912. }
  14913. #endif
  14914. #ifdef _WIN32
  14915. TEST(CleanupTest, WSACleanup) {
  14916. int ret = WSACleanup();
  14917. ASSERT_EQ(0, ret);
  14918. }
  14919. #endif
  14920. #ifndef CPPHTTPLIB_SSL_ENABLED
  14921. TEST(NoSSLSupport, SimpleInterface) {
  14922. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14923. }
  14924. #endif
  14925. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14926. TEST(InvalidScheme, SimpleInterface) {
  14927. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14928. }
  14929. #endif
  14930. TEST(NoScheme, SimpleInterface) {
  14931. Client cli("yahoo.com:80");
  14932. ASSERT_TRUE(cli.is_valid());
  14933. }
  14934. TEST(SendAPI, SimpleInterface_Online) {
  14935. Client cli("http://yahoo.com");
  14936. Request req;
  14937. req.method = "GET";
  14938. req.path = "/";
  14939. auto res = cli.send(req);
  14940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14942. }
  14943. TEST(SendAPI, WithParamsInRequest) {
  14944. Server svr;
  14945. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14946. EXPECT_TRUE(req.has_param("test"));
  14947. EXPECT_EQ("test_value", req.get_param_value("test"));
  14948. });
  14949. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14950. auto se = detail::scope_exit([&] {
  14951. svr.stop();
  14952. t.join();
  14953. ASSERT_FALSE(svr.is_running());
  14954. });
  14955. svr.wait_until_ready();
  14956. Client cli(HOST, PORT);
  14957. {
  14958. Request req;
  14959. req.method = "GET";
  14960. req.path = "/";
  14961. req.params.emplace("test", "test_value");
  14962. auto res = cli.send(req);
  14963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14964. }
  14965. {
  14966. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14968. }
  14969. }
  14970. TEST(ClientImplMethods, GetSocketTest) {
  14971. httplib::Server svr;
  14972. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14973. res.status = StatusCode::OK_200;
  14974. });
  14975. auto port = svr.bind_to_any_port("127.0.0.1");
  14976. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14977. auto se = detail::scope_exit([&] {
  14978. svr.stop();
  14979. thread.join();
  14980. ASSERT_FALSE(svr.is_running());
  14981. });
  14982. svr.wait_until_ready();
  14983. {
  14984. httplib::Client cli("127.0.0.1", port);
  14985. cli.set_keep_alive(true);
  14986. // Use the behavior of cpp-httplib of opening the connection
  14987. // only when the first request happens. If that changes,
  14988. // this test would be obsolete.
  14989. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14990. // This also implicitly tests the server. But other tests would fail much
  14991. // earlier than this one to be considered.
  14992. auto res = cli.Get("/");
  14993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14994. EXPECT_EQ(StatusCode::OK_200, res->status);
  14995. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14996. }
  14997. }
  14998. #ifdef CPPHTTPLIB_SSL_ENABLED
  14999. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15000. Client cli("http://yahoo.com");
  15001. auto res = cli.Get("/");
  15002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15003. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15004. cli.set_follow_location(true);
  15005. res = cli.Get("/");
  15006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15007. EXPECT_EQ(StatusCode::OK_200, res->status);
  15008. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15009. }
  15010. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15011. Client cli("https://yahoo.com");
  15012. auto res = cli.Get("/");
  15013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15014. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15015. cli.set_follow_location(true);
  15016. res = cli.Get("/");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. EXPECT_EQ(StatusCode::OK_200, res->status);
  15019. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15020. }
  15021. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15022. Client cli("https://yahoo.com");
  15023. auto res = cli.Get("/");
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. ASSERT_FALSE(!res);
  15026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15027. ASSERT_FALSE(res == nullptr);
  15028. ASSERT_TRUE(res != nullptr);
  15029. EXPECT_EQ(Error::Success, res.error());
  15030. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15031. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15032. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15033. cli.set_follow_location(true);
  15034. res = cli.Get("/");
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. EXPECT_EQ(Error::Success, res.error());
  15037. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15038. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15039. EXPECT_EQ(StatusCode::OK_200, res->status);
  15040. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15041. }
  15042. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15043. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15044. Client cli("https://cdnjs.cloudflare.com");
  15045. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15046. Headers{{"Accept-Encoding", "br"}});
  15047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15048. EXPECT_EQ(StatusCode::OK_200, res->status);
  15049. EXPECT_EQ(287630U, res->body.size());
  15050. EXPECT_EQ("application/javascript; charset=utf-8",
  15051. res->get_header_value("Content-Type"));
  15052. }
  15053. #endif
  15054. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15055. #undef REDIR_HOST // Silence compiler warning
  15056. #define REDIR_HOST "https://httpbingo.org"
  15057. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15058. Client cli(REDIR_HOST);
  15059. cli.set_follow_location(true);
  15060. auto res =
  15061. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(StatusCode::OK_200, res->status);
  15064. }
  15065. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15066. Client cli(REDIR_HOST);
  15067. cli.set_follow_location(true);
  15068. Params params;
  15069. params.emplace("url", "http://example.com");
  15070. params.emplace("status_code", "302");
  15071. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15073. EXPECT_EQ(StatusCode::OK_200, res->status);
  15074. }
  15075. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15076. Client cli(REDIR_HOST);
  15077. cli.set_follow_location(true);
  15078. Params params;
  15079. params.emplace("url", "http://example.com");
  15080. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15082. EXPECT_EQ(StatusCode::OK_200, res->status);
  15083. }
  15084. TEST(HttpToHttpsRedirectTest, CertFile) {
  15085. auto ssl_port = PORT + 1;
  15086. Server svr;
  15087. ASSERT_TRUE(svr.is_valid());
  15088. svr.Get("/index", [&](const Request &, Response &res) {
  15089. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15090. "/index");
  15091. svr.stop();
  15092. });
  15093. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15094. ASSERT_TRUE(ssl_svr.is_valid());
  15095. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15096. res.set_content("test", "text/plain");
  15097. ssl_svr.stop();
  15098. });
  15099. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15100. thread t2 =
  15101. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15102. auto se = detail::scope_exit([&] {
  15103. t2.join();
  15104. t.join();
  15105. ASSERT_FALSE(svr.is_running());
  15106. });
  15107. svr.wait_until_ready();
  15108. ssl_svr.wait_until_ready();
  15109. Client cli("127.0.0.1", PORT);
  15110. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15111. cli.enable_server_certificate_verification(true);
  15112. cli.set_follow_location(true);
  15113. cli.set_connection_timeout(30);
  15114. auto res = cli.Get("/index");
  15115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15116. ASSERT_EQ(StatusCode::OK_200, res->status);
  15117. }
  15118. TEST(SSLClientRedirectTest, CertFile) {
  15119. auto ssl_port = PORT + 1;
  15120. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15121. ASSERT_TRUE(ssl_svr1.is_valid());
  15122. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15123. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15124. "/index");
  15125. ssl_svr1.stop();
  15126. });
  15127. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15128. ASSERT_TRUE(ssl_svr2.is_valid());
  15129. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15130. res.set_content("test", "text/plain");
  15131. ssl_svr2.stop();
  15132. });
  15133. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15134. thread t2 =
  15135. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15136. auto se = detail::scope_exit([&] {
  15137. t2.join();
  15138. t.join();
  15139. ASSERT_FALSE(ssl_svr1.is_running());
  15140. });
  15141. ssl_svr1.wait_until_ready();
  15142. ssl_svr2.wait_until_ready();
  15143. SSLClient cli("127.0.0.1", PORT);
  15144. std::string cert;
  15145. read_file(SERVER_CERT2_FILE, cert);
  15146. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15147. cli.enable_server_certificate_verification(true);
  15148. cli.set_follow_location(true);
  15149. cli.set_connection_timeout(30);
  15150. auto res = cli.Get("/index");
  15151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15152. ASSERT_EQ(StatusCode::OK_200, res->status);
  15153. }
  15154. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15155. // another port, so the client follows it with a new client.
  15156. static Result GetThroughTlsRedirectToDifferentPort(
  15157. const std::function<void(SSLClient &)> &setup,
  15158. const char *target_cert = SERVER_CERT2_FILE,
  15159. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15160. auto ssl_port = PORT + 1;
  15161. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15162. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15163. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15164. "/index");
  15165. });
  15166. SSLServer ssl_svr2(target_cert, target_key);
  15167. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15168. res.set_content("test", "text/plain");
  15169. });
  15170. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15171. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15172. auto se = detail::scope_exit([&] {
  15173. ssl_svr2.stop();
  15174. ssl_svr1.stop();
  15175. t2.join();
  15176. t.join();
  15177. });
  15178. ssl_svr1.wait_until_ready();
  15179. ssl_svr2.wait_until_ready();
  15180. SSLClient cli("127.0.0.1", PORT);
  15181. cli.set_follow_location(true);
  15182. cli.set_connection_timeout(30);
  15183. setup(cli);
  15184. return cli.Get("/index");
  15185. }
  15186. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15187. auto calls = 0;
  15188. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15189. cli.enable_server_certificate_verification(false);
  15190. // Accept the first server only.
  15191. cli.set_session_verifier([&](tls::session_t) {
  15192. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15193. : SSLVerifierResponse::CertificateRejected;
  15194. });
  15195. });
  15196. ASSERT_FALSE(res);
  15197. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15198. EXPECT_EQ(2, calls);
  15199. }
  15200. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15201. std::string pinned;
  15202. auto res = GetThroughTlsRedirectToDifferentPort(
  15203. [&](SSLClient &cli) {
  15204. cli.enable_server_certificate_verification(false);
  15205. // Pin the first certificate seen.
  15206. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15207. if (pinned.empty()) { pinned = ctx.serial(); }
  15208. return ctx.serial() == pinned;
  15209. });
  15210. },
  15211. // A certificate other than the first server's.
  15212. SERVER_CERT_FILE);
  15213. EXPECT_FALSE(res);
  15214. EXPECT_FALSE(pinned.empty());
  15215. }
  15216. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15217. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15218. std::string cert;
  15219. read_file(SERVER_CERT2_FILE, cert);
  15220. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15221. });
  15222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15223. EXPECT_EQ(StatusCode::OK_200, res->status);
  15224. }
  15225. // The target's certificate is signed by the root CA, which the first server's
  15226. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15227. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15228. auto res = GetThroughTlsRedirectToDifferentPort(
  15229. [](SSLClient &cli) {
  15230. std::string root_ca, cert;
  15231. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15232. read_file(SERVER_CERT2_FILE, cert);
  15233. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15234. cli.load_ca_cert_store(cert.data(), cert.size());
  15235. cli.enable_server_hostname_verification(false);
  15236. },
  15237. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15239. EXPECT_EQ(StatusCode::OK_200, res->status);
  15240. }
  15241. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15242. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15243. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15244. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15245. auto res = GetThroughTlsRedirectToDifferentPort(
  15246. [](SSLClient &cli) {
  15247. std::string root_ca, cert;
  15248. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15249. read_file(SERVER_CERT2_FILE, cert);
  15250. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15251. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15252. cli.enable_server_hostname_verification(false);
  15253. },
  15254. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15255. ASSERT_FALSE(res);
  15256. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15257. }
  15258. #endif
  15259. #endif
  15260. #ifdef CPPHTTPLIB_SSL_ENABLED
  15261. // Test that set_ca_cert_store() skips system certs (consistent with
  15262. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15263. // should be trusted - system certs should NOT be loaded.
  15264. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15265. // Load a specific cert that is NOT a system CA cert
  15266. std::string cert;
  15267. read_file(SERVER_CERT2_FILE, cert);
  15268. SSLClient cli("google.com");
  15269. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15270. cli.enable_server_certificate_verification(true);
  15271. // This should FAIL because:
  15272. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15273. // 2. System certs should NOT be loaded when custom store is set
  15274. // If system certs WERE loaded, this would succeed
  15275. auto res = cli.Get("/");
  15276. ASSERT_FALSE(res);
  15277. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15278. }
  15279. // Same as above, but through the native store handle path. Regression test:
  15280. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15281. // merged system certs into the user-provided store.
  15282. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15283. std::string cert;
  15284. read_file(SERVER_CERT2_FILE, cert);
  15285. SSLClient cli("google.com");
  15286. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15287. cli.enable_server_certificate_verification(true);
  15288. auto res = cli.Get("/");
  15289. ASSERT_FALSE(res);
  15290. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15291. }
  15292. // A custom store set via the native handle must still verify a server whose
  15293. // cert it does contain.
  15294. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15295. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15296. ASSERT_TRUE(svr.is_valid());
  15297. svr.Get("/test", [&](const Request &, Response &res) {
  15298. res.set_content("test", "text/plain");
  15299. });
  15300. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15301. auto se = detail::scope_exit([&] {
  15302. svr.stop();
  15303. t.join();
  15304. ASSERT_FALSE(svr.is_running());
  15305. });
  15306. svr.wait_until_ready();
  15307. SSLClient cli("127.0.0.1", PORT);
  15308. std::string cert;
  15309. read_file(SERVER_CERT2_FILE, cert);
  15310. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15311. cli.enable_server_certificate_verification(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/test");
  15314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15315. ASSERT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. // CA certs loaded through the universal Client must be transferred to the
  15318. // client created internally for following an HTTPS redirect. Regression test:
  15319. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15320. // the CA data for redirect transfer.
  15321. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15322. auto ssl_port = PORT + 1;
  15323. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15324. ASSERT_TRUE(ssl_svr1.is_valid());
  15325. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15326. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15327. "/index");
  15328. });
  15329. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15330. ASSERT_TRUE(ssl_svr2.is_valid());
  15331. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15332. res.set_content("test", "text/plain");
  15333. });
  15334. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15335. thread t2 =
  15336. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15337. auto se = detail::scope_exit([&] {
  15338. ssl_svr2.stop();
  15339. ssl_svr1.stop();
  15340. t2.join();
  15341. t.join();
  15342. ASSERT_FALSE(ssl_svr1.is_running());
  15343. });
  15344. ssl_svr1.wait_until_ready();
  15345. ssl_svr2.wait_until_ready();
  15346. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15347. std::string cert;
  15348. read_file(SERVER_CERT2_FILE, cert);
  15349. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15350. cli.enable_server_certificate_verification(true);
  15351. cli.set_follow_location(true);
  15352. cli.set_connection_timeout(30);
  15353. auto res = cli.Get("/index");
  15354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15355. ASSERT_EQ(StatusCode::OK_200, res->status);
  15356. }
  15357. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15358. // so a host signed by a system CA verifies even though a custom CA is set
  15359. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15360. std::string cert;
  15361. read_file(SERVER_CERT2_FILE, cert);
  15362. SSLClient cli("google.com");
  15363. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15364. cli.enable_system_ca(true);
  15365. cli.enable_server_certificate_verification(true);
  15366. auto res = cli.Get("/");
  15367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15368. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15369. }
  15370. // The custom CA remains effective when combined with the system CA
  15371. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15372. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15373. ASSERT_TRUE(svr.is_valid());
  15374. svr.Get("/test", [&](const Request &, Response &res) {
  15375. res.set_content("test", "text/plain");
  15376. });
  15377. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15378. auto se = detail::scope_exit([&] {
  15379. svr.stop();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. });
  15383. svr.wait_until_ready();
  15384. SSLClient cli("127.0.0.1", PORT);
  15385. std::string cert;
  15386. read_file(SERVER_CERT2_FILE, cert);
  15387. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15388. cli.enable_system_ca(true);
  15389. cli.enable_server_certificate_verification(true);
  15390. cli.set_connection_timeout(30);
  15391. auto res = cli.Get("/test");
  15392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15393. ASSERT_EQ(StatusCode::OK_200, res->status);
  15394. }
  15395. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15396. // skip chain verification entirely (only the certificate identity was
  15397. // checked), so a server presenting an untrusted certificate with a matching
  15398. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15399. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15400. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15401. ASSERT_TRUE(svr.is_valid());
  15402. svr.Get("/test", [&](const Request &, Response &res) {
  15403. res.set_content("test", "text/plain");
  15404. });
  15405. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15406. auto se = detail::scope_exit([&] {
  15407. svr.stop();
  15408. t.join();
  15409. ASSERT_FALSE(svr.is_running());
  15410. });
  15411. svr.wait_until_ready();
  15412. SSLClient cli("127.0.0.1", PORT);
  15413. std::string cert;
  15414. // A trusted CA that did not sign the server certificate. The server cert
  15415. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15416. // this connection.
  15417. read_file(CLIENT_CA_CERT_FILE, cert);
  15418. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15419. cli.enable_server_certificate_verification(true);
  15420. cli.set_connection_timeout(30);
  15421. auto res = cli.Get("/test");
  15422. ASSERT_FALSE(res);
  15423. }
  15424. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15425. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15426. // CA that failed to come through fails verification instead of trusting them.
  15427. // (wolfSSL does not list the system CAs it loaded.)
  15428. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15429. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15430. ASSERT_TRUE(svr.is_valid());
  15431. auto port = svr.bind_to_any_port("127.0.0.1");
  15432. ASSERT_LT(0, port);
  15433. thread t = thread([&] { svr.listen_after_bind(); });
  15434. auto se = detail::scope_exit([&] {
  15435. svr.stop();
  15436. t.join();
  15437. ASSERT_FALSE(svr.is_running());
  15438. });
  15439. svr.wait_until_ready();
  15440. // The CAs a client trusts once its first request has loaded them
  15441. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15442. Client cli("https://127.0.0.1:" + std::to_string(port));
  15443. setup(cli);
  15444. cli.Get("/");
  15445. return tls::get_ca_names(cli.tls_context()).size();
  15446. };
  15447. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15448. EXPECT_EQ(0u,
  15449. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15450. }
  15451. #endif
  15452. // A TLS setting changed between requests applies to the next one, not just to
  15453. // the next connection
  15454. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15455. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15456. ASSERT_TRUE(svr.is_valid());
  15457. svr.Get("/", [](const Request &req, Response &res) {
  15458. res.set_content(std::to_string(req.remote_port), "text/plain");
  15459. });
  15460. auto port = svr.bind_to_any_port("127.0.0.1");
  15461. ASSERT_LT(0, port);
  15462. thread t = thread([&] { svr.listen_after_bind(); });
  15463. auto se = detail::scope_exit([&] {
  15464. svr.stop();
  15465. t.join();
  15466. ASSERT_FALSE(svr.is_running());
  15467. });
  15468. svr.wait_until_ready();
  15469. SSLClient cli("127.0.0.1", port);
  15470. cli.set_keep_alive(true);
  15471. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15472. cli.enable_server_certificate_verification(false);
  15473. // The port the request went out from, so a new one means a new connection
  15474. auto client_port = [&] {
  15475. auto res = cli.Get("/");
  15476. return res ? res->body : std::string();
  15477. };
  15478. auto last = client_port();
  15479. ASSERT_FALSE(last.empty());
  15480. // Setting a value it already has keeps the connection
  15481. cli.enable_server_certificate_verification(false);
  15482. cli.enable_server_hostname_verification(true);
  15483. EXPECT_EQ(last, client_port());
  15484. cli.enable_server_certificate_verification(true);
  15485. auto res = cli.Get("/");
  15486. EXPECT_FALSE(res);
  15487. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15488. std::string ca;
  15489. read_file(SERVER_CERT2_FILE, ca);
  15490. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15491. last = client_port();
  15492. ASSERT_FALSE(last.empty());
  15493. std::vector<std::function<void()>> setters = {
  15494. [&] { cli.enable_server_hostname_verification(false); },
  15495. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15496. [&] {
  15497. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15498. },
  15499. [&] {
  15500. cli.set_server_certificate_verifier(
  15501. [](const tls::VerifyContext &) { return true; });
  15502. },
  15503. [&] {
  15504. cli.set_session_verifier(
  15505. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15506. },
  15507. };
  15508. for (const auto &setter : setters) {
  15509. setter();
  15510. auto next = client_port();
  15511. ASSERT_FALSE(next.empty());
  15512. EXPECT_NE(last, next);
  15513. last = next;
  15514. }
  15515. cli.set_session_verifier(
  15516. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15517. auto handle = cli.open_stream("GET", "/");
  15518. EXPECT_FALSE(handle.is_valid());
  15519. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15520. }
  15521. // A PEM given to create_ca_store() needs no NUL after it
  15522. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15523. std::string pem;
  15524. read_file(SERVER_CERT2_FILE, pem);
  15525. auto buf = pem + "X";
  15526. auto store = tls::create_ca_store(buf.data(), pem.size());
  15527. EXPECT_TRUE(store != nullptr);
  15528. SSLClient cli("localhost");
  15529. cli.set_ca_cert_store(store);
  15530. }
  15531. // enable_system_ca(false) prevents system CA loading entirely
  15532. TEST(SSLClientTest, DisableSystemCa_Online) {
  15533. SSLClient cli("google.com");
  15534. cli.enable_system_ca(false);
  15535. cli.enable_server_certificate_verification(true);
  15536. auto res = cli.Get("/");
  15537. ASSERT_FALSE(res);
  15538. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15539. // itself when the CA chain is empty
  15540. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15541. res.error() == Error::SSLConnection);
  15542. }
  15543. // The universal Client forwards enable_system_ca()
  15544. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15545. std::string cert;
  15546. read_file(SERVER_CERT2_FILE, cert);
  15547. Client cli("https://google.com");
  15548. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15549. cli.enable_system_ca(true);
  15550. cli.enable_server_certificate_verification(true);
  15551. auto res = cli.Get("/");
  15552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15553. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15554. }
  15555. // The system CA policy must carry over to the client created internally for
  15556. // following a cross-host HTTPS redirect
  15557. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15558. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15559. ASSERT_TRUE(svr.is_valid());
  15560. svr.Get("/index", [&](const Request &, Response &res) {
  15561. res.set_redirect("https://www.google.com/");
  15562. });
  15563. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15564. auto se = detail::scope_exit([&] {
  15565. svr.stop();
  15566. t.join();
  15567. ASSERT_FALSE(svr.is_running());
  15568. });
  15569. svr.wait_until_ready();
  15570. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15571. std::string cert;
  15572. read_file(SERVER_CERT2_FILE, cert);
  15573. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15574. cli.enable_system_ca(true);
  15575. cli.enable_server_certificate_verification(true);
  15576. cli.set_follow_location(true);
  15577. cli.set_connection_timeout(30);
  15578. // Receiving any response proves the redirect client completed the TLS
  15579. // handshake with a system-CA-signed host
  15580. auto res = cli.Get("/index");
  15581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15582. }
  15583. TEST(MultipartFormDataTest, LargeData) {
  15584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15585. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15586. const ContentReader &content_reader) {
  15587. if (req.is_multipart_form_data()) {
  15588. std::vector<FormData> items;
  15589. content_reader(
  15590. [&](const FormData &file) {
  15591. items.push_back(file);
  15592. return true;
  15593. },
  15594. [&](const char *data, size_t data_length) {
  15595. items.back().content.append(data, data_length);
  15596. return true;
  15597. });
  15598. EXPECT_TRUE(std::string(items[0].name) == "document");
  15599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15600. EXPECT_TRUE(items[0].filename == "2MB_data");
  15601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15602. EXPECT_TRUE(items[1].name == "hello");
  15603. EXPECT_TRUE(items[1].content == "world");
  15604. EXPECT_TRUE(items[1].filename == "");
  15605. EXPECT_TRUE(items[1].content_type == "");
  15606. } else {
  15607. std::string body;
  15608. content_reader([&](const char *data, size_t data_length) {
  15609. body.append(data, data_length);
  15610. return true;
  15611. });
  15612. }
  15613. });
  15614. auto port = svr.bind_to_any_port(HOST);
  15615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15616. auto se = detail::scope_exit([&] {
  15617. svr.stop();
  15618. t.join();
  15619. ASSERT_FALSE(svr.is_running());
  15620. });
  15621. svr.wait_until_ready();
  15622. {
  15623. std::string data(1024 * 1024 * 2, '.');
  15624. std::stringstream buffer;
  15625. buffer << data;
  15626. SSLClient cli(HOST, port);
  15627. cli.enable_server_certificate_verification(false);
  15628. UploadFormDataItems items{
  15629. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15630. {"hello", "world", "", ""},
  15631. };
  15632. auto res = cli.Post("/post", items);
  15633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15634. ASSERT_EQ(StatusCode::OK_200, res->status);
  15635. }
  15636. }
  15637. TEST(MultipartFormDataTest, DataProviderItems) {
  15638. std::random_device seed_gen;
  15639. std::mt19937 random(seed_gen());
  15640. std::string rand1;
  15641. rand1.resize(1000);
  15642. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15643. std::string rand2;
  15644. rand2.resize(3000);
  15645. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15647. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15648. const ContentReader &content_reader) {
  15649. ASSERT_FALSE(req.is_multipart_form_data());
  15650. std::string body;
  15651. content_reader([&](const char *data, size_t data_length) {
  15652. body.append(data, data_length);
  15653. return true;
  15654. });
  15655. EXPECT_EQ(body, "");
  15656. });
  15657. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15658. const ContentReader &content_reader) {
  15659. ASSERT_TRUE(req.is_multipart_form_data());
  15660. std::vector<FormData> items;
  15661. content_reader(
  15662. [&](const FormData &file) {
  15663. items.push_back(file);
  15664. return true;
  15665. },
  15666. [&](const char *data, size_t data_length) {
  15667. items.back().content.append(data, data_length);
  15668. return true;
  15669. });
  15670. ASSERT_TRUE(items.size() == 2);
  15671. EXPECT_EQ(std::string(items[0].name), "name1");
  15672. EXPECT_EQ(items[0].content, "Testing123");
  15673. EXPECT_EQ(items[0].filename, "filename1");
  15674. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15675. EXPECT_EQ(items[1].name, "name2");
  15676. EXPECT_EQ(items[1].content, "Testing456");
  15677. EXPECT_EQ(items[1].filename, "");
  15678. EXPECT_EQ(items[1].content_type, "");
  15679. });
  15680. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15681. const ContentReader &content_reader) {
  15682. ASSERT_TRUE(req.is_multipart_form_data());
  15683. std::vector<FormData> items;
  15684. content_reader(
  15685. [&](const FormData &file) {
  15686. items.push_back(file);
  15687. return true;
  15688. },
  15689. [&](const char *data, size_t data_length) {
  15690. items.back().content.append(data, data_length);
  15691. return true;
  15692. });
  15693. ASSERT_TRUE(items.size() == 2);
  15694. EXPECT_EQ(items[0].name, "name3");
  15695. EXPECT_EQ(items[0].content, rand1);
  15696. EXPECT_EQ(items[0].filename, "filename3");
  15697. EXPECT_EQ(items[0].content_type, "");
  15698. EXPECT_EQ(items[1].name, "name4");
  15699. EXPECT_EQ(items[1].content, rand2);
  15700. EXPECT_EQ(items[1].filename, "filename4");
  15701. EXPECT_EQ(items[1].content_type, "");
  15702. });
  15703. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15704. const ContentReader &content_reader) {
  15705. ASSERT_TRUE(req.is_multipart_form_data());
  15706. std::vector<FormData> items;
  15707. content_reader(
  15708. [&](const FormData &file) {
  15709. items.push_back(file);
  15710. return true;
  15711. },
  15712. [&](const char *data, size_t data_length) {
  15713. items.back().content.append(data, data_length);
  15714. return true;
  15715. });
  15716. ASSERT_TRUE(items.size() == 4);
  15717. EXPECT_EQ(std::string(items[0].name), "name1");
  15718. EXPECT_EQ(items[0].content, "Testing123");
  15719. EXPECT_EQ(items[0].filename, "filename1");
  15720. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15721. EXPECT_EQ(items[1].name, "name2");
  15722. EXPECT_EQ(items[1].content, "Testing456");
  15723. EXPECT_EQ(items[1].filename, "");
  15724. EXPECT_EQ(items[1].content_type, "");
  15725. EXPECT_EQ(items[2].name, "name3");
  15726. EXPECT_EQ(items[2].content, rand1);
  15727. EXPECT_EQ(items[2].filename, "filename3");
  15728. EXPECT_EQ(items[2].content_type, "");
  15729. EXPECT_EQ(items[3].name, "name4");
  15730. EXPECT_EQ(items[3].content, rand2);
  15731. EXPECT_EQ(items[3].filename, "filename4");
  15732. EXPECT_EQ(items[3].content_type, "");
  15733. });
  15734. auto port = svr.bind_to_any_port("localhost");
  15735. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15736. auto se = detail::scope_exit([&] {
  15737. svr.stop();
  15738. t.join();
  15739. ASSERT_FALSE(svr.is_running());
  15740. });
  15741. svr.wait_until_ready();
  15742. {
  15743. SSLClient cli("localhost", port);
  15744. cli.enable_server_certificate_verification(false);
  15745. UploadFormDataItems items{
  15746. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15747. {"name2", "Testing456", "", ""}, // not a file
  15748. };
  15749. {
  15750. auto res = cli.Post("/post-none", {}, {}, {});
  15751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15752. ASSERT_EQ(StatusCode::OK_200, res->status);
  15753. }
  15754. FormDataProviderItems providers;
  15755. {
  15756. auto res =
  15757. cli.Post("/post-items", {}, items, providers); // empty providers
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. ASSERT_EQ(StatusCode::OK_200, res->status);
  15760. }
  15761. providers.push_back({"name3",
  15762. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15763. // test the offset is given correctly at each step
  15764. if (!offset)
  15765. sink.os.write(rand1.data(), 30);
  15766. else if (offset == 30)
  15767. sink.os.write(rand1.data() + 30, 300);
  15768. else if (offset == 330)
  15769. sink.os.write(rand1.data() + 330, 670);
  15770. else if (offset == rand1.size())
  15771. sink.done();
  15772. return true;
  15773. },
  15774. "filename3",
  15775. {}});
  15776. providers.push_back({"name4",
  15777. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15778. // test the offset is given correctly at each step
  15779. if (!offset)
  15780. sink.os.write(rand2.data(), 2000);
  15781. else if (offset == 2000)
  15782. sink.os.write(rand2.data() + 2000, 1);
  15783. else if (offset == 2001)
  15784. sink.os.write(rand2.data() + 2001, 999);
  15785. else if (offset == rand2.size())
  15786. sink.done();
  15787. return true;
  15788. },
  15789. "filename4",
  15790. {}});
  15791. {
  15792. auto res = cli.Post("/post-providers", {}, {}, providers);
  15793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15794. ASSERT_EQ(StatusCode::OK_200, res->status);
  15795. }
  15796. {
  15797. auto res = cli.Post("/post-both", {}, items, providers);
  15798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15799. ASSERT_EQ(StatusCode::OK_200, res->status);
  15800. }
  15801. }
  15802. }
  15803. TEST(MultipartFormDataTest, BadHeader) {
  15804. Server svr;
  15805. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15806. res.set_content("ok", "text/plain");
  15807. });
  15808. thread t = thread([&] { svr.listen(HOST, PORT); });
  15809. auto se = detail::scope_exit([&] {
  15810. svr.stop();
  15811. t.join();
  15812. ASSERT_FALSE(svr.is_running());
  15813. });
  15814. svr.wait_until_ready();
  15815. const std::string body =
  15816. "This is the preamble. It is to be ignored, though it\r\n"
  15817. "is a handy place for composition agents to include an\r\n"
  15818. "explanatory note to non-MIME conformant readers.\r\n"
  15819. "\r\n"
  15820. "\r\n"
  15821. "--simple boundary\r\n"
  15822. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15823. ": BAD...\r\n"
  15824. "\r\n"
  15825. "value1\r\n"
  15826. "--simple boundary\r\n"
  15827. "Content-Disposition: form-data; name=\"field2\"; "
  15828. "filename=\"example.txt\"\r\n"
  15829. "\r\n"
  15830. "value2\r\n"
  15831. "--simple boundary--\r\n"
  15832. "This is the epilogue. It is also to be ignored.\r\n";
  15833. std::string content_type =
  15834. R"(multipart/form-data; boundary="simple boundary")";
  15835. Client cli(HOST, PORT);
  15836. auto res = cli.Post("/post", body, content_type.c_str());
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15839. }
  15840. TEST(MultipartFormDataTest, WithPreamble) {
  15841. Server svr;
  15842. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15843. res.set_content("ok", "text/plain");
  15844. });
  15845. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. const std::string body =
  15853. "This is the preamble. It is to be ignored, though it\r\n"
  15854. "is a handy place for composition agents to include an\r\n"
  15855. "explanatory note to non-MIME conformant readers.\r\n"
  15856. "\r\n"
  15857. "\r\n"
  15858. "--simple boundary\r\n"
  15859. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15860. "\r\n"
  15861. "value1\r\n"
  15862. "--simple boundary\r\n"
  15863. "Content-Disposition: form-data; name=\"field2\"; "
  15864. "filename=\"example.txt\"\r\n"
  15865. "\r\n"
  15866. "value2\r\n"
  15867. "--simple boundary--\r\n"
  15868. "This is the epilogue. It is also to be ignored.\r\n";
  15869. std::string content_type =
  15870. R"(multipart/form-data; boundary="simple boundary")";
  15871. Client cli(HOST, PORT);
  15872. auto res = cli.Post("/post", body, content_type.c_str());
  15873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15874. EXPECT_EQ(StatusCode::OK_200, res->status);
  15875. }
  15876. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15878. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15879. const ContentReader &content_reader) {
  15880. if (req.is_multipart_form_data()) {
  15881. std::vector<FormData> items;
  15882. content_reader(
  15883. [&](const FormData &file) {
  15884. items.push_back(file);
  15885. return true;
  15886. },
  15887. [&](const char *data, size_t data_length) {
  15888. items.back().content.append(data, data_length);
  15889. return true;
  15890. });
  15891. EXPECT_TRUE(std::string(items[0].name) == "document");
  15892. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15893. EXPECT_TRUE(items[0].filename == "2MB_data");
  15894. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15895. EXPECT_TRUE(items[1].name == "hello");
  15896. EXPECT_TRUE(items[1].content == "world");
  15897. EXPECT_TRUE(items[1].filename == "");
  15898. EXPECT_TRUE(items[1].content_type == "");
  15899. } else {
  15900. std::string body;
  15901. content_reader([&](const char *data, size_t data_length) {
  15902. body.append(data, data_length);
  15903. return true;
  15904. });
  15905. }
  15906. });
  15907. auto port = svr.bind_to_any_port("localhost");
  15908. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15909. auto se = detail::scope_exit([&] {
  15910. svr.stop();
  15911. t.join();
  15912. ASSERT_FALSE(svr.is_running());
  15913. });
  15914. svr.wait_until_ready();
  15915. {
  15916. std::string data(1024 * 1024 * 2, '.');
  15917. std::stringstream buffer;
  15918. buffer << data;
  15919. SSLClient cli("localhost", port);
  15920. cli.enable_server_certificate_verification(false);
  15921. UploadFormDataItems items{
  15922. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15923. {"hello", "world", "", ""},
  15924. };
  15925. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. ASSERT_EQ(StatusCode::OK_200, res->status);
  15928. }
  15929. }
  15930. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15931. std::string data(1024 * 1024 * 2, '&');
  15932. std::stringstream buffer;
  15933. buffer << data;
  15934. Client cli("https://localhost:8080");
  15935. UploadFormDataItems items{
  15936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15937. {"hello", "world", "", ""},
  15938. };
  15939. for (const char &c : " \t\r\n") {
  15940. auto res =
  15941. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15942. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15943. ASSERT_FALSE(res);
  15944. }
  15945. }
  15946. TEST(MultipartFormDataTest, PutFormData) {
  15947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15948. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15949. const ContentReader &content_reader) {
  15950. if (req.is_multipart_form_data()) {
  15951. std::vector<FormData> items;
  15952. content_reader(
  15953. [&](const FormData &file) {
  15954. items.push_back(file);
  15955. return true;
  15956. },
  15957. [&](const char *data, size_t data_length) {
  15958. items.back().content.append(data, data_length);
  15959. return true;
  15960. });
  15961. EXPECT_TRUE(std::string(items[0].name) == "document");
  15962. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15963. EXPECT_TRUE(items[0].filename == "2MB_data");
  15964. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15965. EXPECT_TRUE(items[1].name == "hello");
  15966. EXPECT_TRUE(items[1].content == "world");
  15967. EXPECT_TRUE(items[1].filename == "");
  15968. EXPECT_TRUE(items[1].content_type == "");
  15969. } else {
  15970. std::string body;
  15971. content_reader([&](const char *data, size_t data_length) {
  15972. body.append(data, data_length);
  15973. return true;
  15974. });
  15975. }
  15976. });
  15977. auto port = svr.bind_to_any_port("localhost");
  15978. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15979. auto se = detail::scope_exit([&] {
  15980. svr.stop();
  15981. t.join();
  15982. ASSERT_FALSE(svr.is_running());
  15983. });
  15984. svr.wait_until_ready();
  15985. {
  15986. std::string data(1024 * 1024 * 2, '&');
  15987. std::stringstream buffer;
  15988. buffer << data;
  15989. SSLClient cli("localhost", port);
  15990. cli.enable_server_certificate_verification(false);
  15991. UploadFormDataItems items{
  15992. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15993. {"hello", "world", "", ""},
  15994. };
  15995. auto res = cli.Put("/put", items);
  15996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15997. ASSERT_EQ(StatusCode::OK_200, res->status);
  15998. }
  15999. }
  16000. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16002. svr.Put("/put_customboundary",
  16003. [&](const Request &req, const Response & /*res*/,
  16004. const ContentReader &content_reader) {
  16005. if (req.is_multipart_form_data()) {
  16006. std::vector<FormData> items;
  16007. content_reader(
  16008. [&](const FormData &file) {
  16009. items.push_back(file);
  16010. return true;
  16011. },
  16012. [&](const char *data, size_t data_length) {
  16013. items.back().content.append(data, data_length);
  16014. return true;
  16015. });
  16016. EXPECT_TRUE(std::string(items[0].name) == "document");
  16017. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16018. EXPECT_TRUE(items[0].filename == "2MB_data");
  16019. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16020. EXPECT_TRUE(items[1].name == "hello");
  16021. EXPECT_TRUE(items[1].content == "world");
  16022. EXPECT_TRUE(items[1].filename == "");
  16023. EXPECT_TRUE(items[1].content_type == "");
  16024. } else {
  16025. std::string body;
  16026. content_reader([&](const char *data, size_t data_length) {
  16027. body.append(data, data_length);
  16028. return true;
  16029. });
  16030. }
  16031. });
  16032. auto port = svr.bind_to_any_port("localhost");
  16033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16034. auto se = detail::scope_exit([&] {
  16035. svr.stop();
  16036. t.join();
  16037. ASSERT_FALSE(svr.is_running());
  16038. });
  16039. svr.wait_until_ready();
  16040. {
  16041. std::string data(1024 * 1024 * 2, '&');
  16042. std::stringstream buffer;
  16043. buffer << data;
  16044. SSLClient cli("localhost", port);
  16045. cli.enable_server_certificate_verification(false);
  16046. UploadFormDataItems items{
  16047. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16048. {"hello", "world", "", ""},
  16049. };
  16050. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16052. ASSERT_EQ(StatusCode::OK_200, res->status);
  16053. }
  16054. }
  16055. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16056. std::string data(1024 * 1024 * 2, '&');
  16057. std::stringstream buffer;
  16058. buffer << data;
  16059. Client cli("https://localhost:8080");
  16060. cli.enable_server_certificate_verification(false);
  16061. UploadFormDataItems items{
  16062. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16063. {"hello", "world", "", ""},
  16064. };
  16065. for (const char &c : " \t\r\n") {
  16066. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16067. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16068. ASSERT_FALSE(res);
  16069. }
  16070. }
  16071. TEST(MultipartFormDataTest, AlternateFilename) {
  16072. auto handled = false;
  16073. Server svr;
  16074. svr.Post("/test", [&](const Request &req, Response &res) {
  16075. ASSERT_EQ(2u, req.form.files.size());
  16076. ASSERT_EQ(1u, req.form.fields.size());
  16077. // Test files
  16078. const auto &file1 = req.form.get_file("file1");
  16079. ASSERT_EQ("file1", file1.name);
  16080. ASSERT_EQ("A.txt", file1.filename);
  16081. ASSERT_EQ("text/plain", file1.content_type);
  16082. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16083. const auto &file2 = req.form.get_file("file2");
  16084. ASSERT_EQ("file2", file2.name);
  16085. ASSERT_EQ("a.html", file2.filename);
  16086. ASSERT_EQ("text/html", file2.content_type);
  16087. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16088. file2.content);
  16089. // Test text field
  16090. const auto &text = req.form.get_field("text");
  16091. ASSERT_EQ("text default", text);
  16092. res.set_content("ok", "text/plain");
  16093. handled = true;
  16094. });
  16095. thread t = thread([&] { svr.listen(HOST, PORT); });
  16096. auto se = detail::scope_exit([&] {
  16097. svr.stop();
  16098. t.join();
  16099. ASSERT_FALSE(svr.is_running());
  16100. ASSERT_TRUE(handled);
  16101. });
  16102. svr.wait_until_ready();
  16103. auto req = "POST /test HTTP/1.1\r\n"
  16104. "Host: localhost\r\n"
  16105. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16106. "Content-Length: 399\r\n"
  16107. "\r\n"
  16108. "----------\r\n"
  16109. "Content-Disposition: form-data; name=\"text\"\r\n"
  16110. "\r\n"
  16111. "text default\r\n"
  16112. "----------\r\n"
  16113. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16114. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16115. "Content-Type: text/plain\r\n"
  16116. "\r\n"
  16117. "Content of a.txt.\r\n"
  16118. "\r\n"
  16119. "----------\r\n"
  16120. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16121. "\"a.html\"\r\n"
  16122. "Content-Type: text/html\r\n"
  16123. "\r\n"
  16124. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16125. "\r\n"
  16126. "------------\r\n";
  16127. ASSERT_TRUE(send_request(1, req));
  16128. }
  16129. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16130. auto handled = false;
  16131. Server svr;
  16132. svr.Post("/test", [&](const Request &req, Response &res) {
  16133. // Case-insensitive "utf-8''" prefix with a long value
  16134. const auto &file = req.form.get_file("file1");
  16135. ASSERT_EQ("file1", file.name);
  16136. // 8000 chars exercises both the Content-Disposition parser and the
  16137. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16138. // Prior to the fix, std::regex_match on this header would cause O(N)
  16139. // stack recursion in libstdc++, leading to SIGSEGV.
  16140. std::string expected_filename(8000, 'A');
  16141. ASSERT_EQ(expected_filename, file.filename);
  16142. res.set_content("ok", "text/plain");
  16143. handled = true;
  16144. });
  16145. thread t = thread([&] { svr.listen(HOST, PORT); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. t.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. ASSERT_TRUE(handled);
  16151. });
  16152. svr.wait_until_ready();
  16153. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16154. // Regression test for GHSA-qq6v-r583-3h69
  16155. std::string long_filename(8000, 'A');
  16156. std::string body = "----------\r\n"
  16157. "Content-Disposition: form-data; name=\"file1\"; "
  16158. "filename*=\"Utf-8''" +
  16159. long_filename +
  16160. "\"\r\n"
  16161. "\r\n"
  16162. "hello\r\n"
  16163. "------------\r\n";
  16164. auto req = "POST /test HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16167. "Content-Length: " +
  16168. std::to_string(body.size()) + "\r\n\r\n" + body;
  16169. ASSERT_TRUE(send_request(1, req));
  16170. }
  16171. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16172. auto handled = false;
  16173. Server svr;
  16174. svr.Post("/test", [&](const Request &req, Response &) {
  16175. ASSERT_EQ(2u, req.form.fields.size());
  16176. const auto &text1 = req.form.get_field("text1");
  16177. ASSERT_EQ("text1", text1);
  16178. const auto &text2 = req.form.get_field("text2");
  16179. ASSERT_EQ("text2", text2);
  16180. handled = true;
  16181. });
  16182. thread t = thread([&] { svr.listen(HOST, PORT); });
  16183. auto se = detail::scope_exit([&] {
  16184. svr.stop();
  16185. t.join();
  16186. ASSERT_FALSE(svr.is_running());
  16187. ASSERT_TRUE(handled);
  16188. });
  16189. svr.wait_until_ready();
  16190. auto req = "POST /test HTTP/1.1\r\n"
  16191. "Host: localhost\r\n"
  16192. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16193. "Content-Length: 146\r\n"
  16194. "\r\n----------\r\n"
  16195. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16196. "\r\n"
  16197. "text1"
  16198. "\r\n----------\r\n"
  16199. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16200. "\r\n"
  16201. "text2"
  16202. "\r\n------------";
  16203. std::string response;
  16204. ASSERT_TRUE(send_request(1, req, &response));
  16205. ASSERT_EQ("200", response.substr(9, 3));
  16206. }
  16207. TEST(MultipartFormDataTest, ContentLength) {
  16208. auto handled = false;
  16209. Server svr;
  16210. svr.Post("/test", [&](const Request &req, Response &) {
  16211. ASSERT_EQ(2u, req.form.fields.size());
  16212. const auto &text1 = req.form.get_field("text1");
  16213. ASSERT_EQ("text1", text1);
  16214. const auto &text2 = req.form.get_field("text2");
  16215. ASSERT_EQ("text2", text2);
  16216. handled = true;
  16217. });
  16218. thread t = thread([&] { svr.listen(HOST, PORT); });
  16219. auto se = detail::scope_exit([&] {
  16220. svr.stop();
  16221. t.join();
  16222. ASSERT_FALSE(svr.is_running());
  16223. ASSERT_TRUE(handled);
  16224. });
  16225. svr.wait_until_ready();
  16226. auto req = "POST /test HTTP/1.1\r\n"
  16227. "Host: localhost\r\n"
  16228. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16229. "Content-Length: 167\r\n"
  16230. "\r\n----------\r\n"
  16231. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16232. "Content-Length: 5\r\n"
  16233. "\r\n"
  16234. "text1"
  16235. "\r\n----------\r\n"
  16236. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16237. "\r\n"
  16238. "text2"
  16239. "\r\n------------\r\n";
  16240. std::string response;
  16241. ASSERT_TRUE(send_request(1, req, &response));
  16242. ASSERT_EQ("200", response.substr(9, 3));
  16243. }
  16244. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16245. auto handled = false;
  16246. Server svr;
  16247. svr.Post("/test", [&](const Request &req, Response &) {
  16248. ASSERT_EQ(2u, req.form.fields.size());
  16249. const auto &text1 = req.form.get_field("text1");
  16250. ASSERT_EQ("text1", text1);
  16251. // TODO: Add header access for text fields if needed
  16252. const auto &text2 = req.form.get_field("text2");
  16253. ASSERT_EQ("text2", text2);
  16254. // TODO: Header access for text fields needs to be implemented
  16255. // auto &headers = it->second.headers;
  16256. // ASSERT_EQ(3U, headers.size());
  16257. // auto custom_header = headers.find("x-whatever");
  16258. // ASSERT_TRUE(custom_header != headers.end());
  16259. // ASSERT_NE("customvalue", custom_header->second);
  16260. // ASSERT_EQ("CustomValue", custom_header->second);
  16261. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16262. handled = true;
  16263. });
  16264. thread t = thread([&] { svr.listen(HOST, PORT); });
  16265. auto se = detail::scope_exit([&] {
  16266. svr.stop();
  16267. t.join();
  16268. ASSERT_FALSE(svr.is_running());
  16269. ASSERT_TRUE(handled);
  16270. });
  16271. svr.wait_until_ready();
  16272. auto req = "POST /test HTTP/1.1\r\n"
  16273. "Host: localhost\r\n"
  16274. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16275. "Content-Length: 232\r\n"
  16276. "\r\n----------\r\n"
  16277. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16278. "Content-Length: 5\r\n"
  16279. "X-Test: 1\r\n"
  16280. "\r\n"
  16281. "text1"
  16282. "\r\n----------\r\n"
  16283. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16284. "Content-Type: text/plain\r\n"
  16285. "X-Whatever: CustomValue\r\n"
  16286. "\r\n"
  16287. "text2"
  16288. "\r\n------------\r\n"
  16289. "That should be disregarded. Not even read";
  16290. std::string response;
  16291. ASSERT_TRUE(send_request(1, req, &response));
  16292. ASSERT_EQ("200", response.substr(9, 3));
  16293. }
  16294. TEST(MultipartFormDataTest, LargeHeader) {
  16295. auto handled = false;
  16296. Server svr;
  16297. svr.Post("/test", [&](const Request &req, Response &) {
  16298. ASSERT_EQ(1u, req.form.fields.size());
  16299. const auto &text = req.form.get_field("name1");
  16300. ASSERT_EQ("text1", text);
  16301. handled = true;
  16302. });
  16303. thread t = thread([&] { svr.listen(HOST, PORT); });
  16304. auto se = detail::scope_exit([&] {
  16305. svr.stop();
  16306. t.join();
  16307. ASSERT_FALSE(svr.is_running());
  16308. ASSERT_TRUE(handled);
  16309. });
  16310. svr.wait_until_ready();
  16311. auto boundary = std::string("cpp-httplib-multipart-data");
  16312. std::string content = "--" + boundary +
  16313. "\r\n"
  16314. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16315. "\r\n"
  16316. "text1\r\n"
  16317. "--" +
  16318. boundary + "--\r\n";
  16319. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16320. "Host: localhost\r\n"
  16321. "Content-Type: multipart/form-data;boundary=" +
  16322. boundary +
  16323. "\r\n"
  16324. "Content-Length: " +
  16325. std::to_string(content.size()) +
  16326. "\r\n"
  16327. "Dummy-Header: ";
  16328. std::string header_suffix = "\r\n"
  16329. "\r\n";
  16330. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16331. size_t header_dummy_size =
  16332. read_buff_size -
  16333. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16334. auto header_dummy = std::string(header_dummy_size, '@');
  16335. auto req = header_prefix + header_dummy + header_suffix + content;
  16336. std::string response;
  16337. ASSERT_TRUE(send_request(1, req, &response));
  16338. ASSERT_EQ("200", response.substr(9, 3));
  16339. }
  16340. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16341. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16342. // (not chunked Transfer-Encoding) after the streaming refactor.
  16343. auto handled = false;
  16344. Server svr;
  16345. svr.Post("/upload", [&](const Request &req, Response &res) {
  16346. auto cl_it = req.headers.find("Content-Length");
  16347. EXPECT_TRUE(cl_it != req.headers.end());
  16348. auto te_it = req.headers.find("Transfer-Encoding");
  16349. EXPECT_TRUE(te_it == req.headers.end());
  16350. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16351. res.set_content("ok", "text/plain");
  16352. handled = true;
  16353. });
  16354. auto port = svr.bind_to_any_port(HOST);
  16355. auto t = thread([&] { svr.listen_after_bind(); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. t.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. ASSERT_TRUE(handled);
  16361. });
  16362. svr.wait_until_ready();
  16363. UploadFormDataItems items = {
  16364. {"field1", "hello", "", "text/plain"},
  16365. {"file1", "world", "test.txt", "application/octet-stream"},
  16366. };
  16367. Client cli(HOST, port);
  16368. auto res = cli.Post("/upload", {}, items);
  16369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16370. EXPECT_EQ(StatusCode::OK_200, res->status);
  16371. }
  16372. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16373. // Verify that make_multipart_content_provider coalesces many small segments
  16374. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16375. constexpr size_t kItemCount = 1000;
  16376. UploadFormDataItems items;
  16377. items.reserve(kItemCount);
  16378. for (size_t i = 0; i < kItemCount; i++) {
  16379. items.push_back(
  16380. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16381. }
  16382. const std::string boundary = "----test-boundary";
  16383. auto content_length = detail::get_multipart_content_length(items, boundary);
  16384. auto provider = detail::make_multipart_content_provider(items, boundary);
  16385. // Drive the provider the same way write_content_with_progress does
  16386. size_t write_count = 0;
  16387. size_t total_bytes = 0;
  16388. DataSink sink;
  16389. size_t offset = 0;
  16390. sink.write = [&](const char *d, size_t l) -> bool {
  16391. (void)d;
  16392. write_count++;
  16393. total_bytes += l;
  16394. offset += l;
  16395. return true;
  16396. };
  16397. sink.is_writable = []() -> bool { return true; };
  16398. while (offset < content_length) {
  16399. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16400. }
  16401. EXPECT_EQ(content_length, total_bytes);
  16402. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16403. // With buffering into 64KB blocks, write_count should be much smaller.
  16404. auto segment_count = 3 * kItemCount + 1;
  16405. EXPECT_LT(write_count, segment_count / 10);
  16406. }
  16407. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16408. // Integration test: send many UploadFormDataItems and verify the server
  16409. // receives all of them correctly (#2410).
  16410. constexpr size_t kItemCount = 500;
  16411. auto handled = false;
  16412. Server svr;
  16413. svr.Post("/upload", [&](const Request &req, Response &res) {
  16414. EXPECT_EQ(kItemCount, req.form.fields.size());
  16415. for (size_t i = 0; i < kItemCount; i++) {
  16416. auto key = "field" + std::to_string(i);
  16417. auto val = "value" + std::to_string(i);
  16418. auto it = req.form.fields.find(key);
  16419. if (it != req.form.fields.end()) {
  16420. EXPECT_EQ(val, it->second.content);
  16421. } else {
  16422. ADD_FAILURE() << "Missing field: " << key;
  16423. }
  16424. }
  16425. res.set_content("ok", "text/plain");
  16426. handled = true;
  16427. });
  16428. auto port = svr.bind_to_any_port(HOST);
  16429. auto t = thread([&] { svr.listen_after_bind(); });
  16430. auto se = detail::scope_exit([&] {
  16431. svr.stop();
  16432. t.join();
  16433. ASSERT_FALSE(svr.is_running());
  16434. ASSERT_TRUE(handled);
  16435. });
  16436. svr.wait_until_ready();
  16437. UploadFormDataItems items;
  16438. items.reserve(kItemCount);
  16439. for (size_t i = 0; i < kItemCount; i++) {
  16440. items.push_back(
  16441. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16442. }
  16443. Client cli(HOST, port);
  16444. auto res = cli.Post("/upload", items);
  16445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16446. EXPECT_EQ(StatusCode::OK_200, res->status);
  16447. }
  16448. TEST(MultipartFormDataTest, MakeFileProvider) {
  16449. // Verify make_file_provider sends a file's contents correctly.
  16450. const std::string file_content(4096, 'Z');
  16451. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16452. {
  16453. std::ofstream ofs(tmp_path, std::ios::binary);
  16454. ofs.write(file_content.data(),
  16455. static_cast<std::streamsize>(file_content.size()));
  16456. }
  16457. auto handled = false;
  16458. Server svr;
  16459. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16460. const ContentReader &content_reader) {
  16461. ASSERT_TRUE(req.is_multipart_form_data());
  16462. std::vector<FormData> items;
  16463. content_reader(
  16464. [&](const FormData &file) {
  16465. items.push_back(file);
  16466. return true;
  16467. },
  16468. [&](const char *data, size_t data_length) {
  16469. items.back().content.append(data, data_length);
  16470. return true;
  16471. });
  16472. ASSERT_EQ(1u, items.size());
  16473. EXPECT_EQ("myfile", items[0].name);
  16474. EXPECT_EQ("data.bin", items[0].filename);
  16475. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16476. EXPECT_EQ(file_content, items[0].content);
  16477. handled = true;
  16478. });
  16479. auto port = svr.bind_to_any_port(HOST);
  16480. auto t = thread([&] { svr.listen_after_bind(); });
  16481. auto se = detail::scope_exit([&] {
  16482. svr.stop();
  16483. t.join();
  16484. ASSERT_FALSE(svr.is_running());
  16485. ASSERT_TRUE(handled);
  16486. std::remove(tmp_path.c_str());
  16487. });
  16488. svr.wait_until_ready();
  16489. FormDataProviderItems providers;
  16490. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16491. "application/octet-stream"));
  16492. Client cli(HOST, port);
  16493. auto res = cli.Post("/upload", {}, {}, providers);
  16494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16495. EXPECT_EQ(StatusCode::OK_200, res->status);
  16496. }
  16497. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16498. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16499. // (100) headers is rejected with a 400 Bad Request response.
  16500. Server svr;
  16501. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16502. res.set_content("ok", "text/plain");
  16503. });
  16504. thread t = thread([&] { svr.listen(HOST, PORT); });
  16505. auto se = detail::scope_exit([&] {
  16506. svr.stop();
  16507. t.join();
  16508. ASSERT_FALSE(svr.is_running());
  16509. });
  16510. svr.wait_until_ready();
  16511. // Build a multipart part with 101 custom headers (exceeding
  16512. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16513. std::stringstream body;
  16514. body << "--simpleboundary\r\n"
  16515. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16516. for (int i = 0; i < 101; i++) {
  16517. body << "X-Custom-Header-" << i << ": value\r\n";
  16518. }
  16519. body << "\r\n"
  16520. << "value1\r\n"
  16521. << "--simpleboundary--\r\n";
  16522. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16523. Client cli(HOST, PORT);
  16524. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16526. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16527. }
  16528. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16529. // A body that never contains the declared boundary must not be accumulated
  16530. // while the parser waits for it. Buffering it would also make every read
  16531. // rescan everything seen so far, which is quadratic in the body size.
  16532. Server svr;
  16533. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16534. res.set_content("ok", "text/plain");
  16535. });
  16536. auto port = svr.bind_to_any_port(HOST);
  16537. thread t = thread([&] { svr.listen_after_bind(); });
  16538. auto se = detail::scope_exit([&] {
  16539. svr.stop();
  16540. t.join();
  16541. ASSERT_FALSE(svr.is_running());
  16542. });
  16543. svr.wait_until_ready();
  16544. Client cli(HOST, port);
  16545. cli.set_read_timeout(60, 0);
  16546. cli.set_write_timeout(60, 0);
  16547. // '-' is the worst case: it matches the first character of the boundary, so
  16548. // every position has to be checked against it.
  16549. auto post_dashes = [&](size_t size) {
  16550. const std::string body(size, '-');
  16551. auto start = std::chrono::steady_clock::now();
  16552. auto res =
  16553. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16554. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16555. std::chrono::steady_clock::now() - start)
  16556. .count();
  16557. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16558. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16559. return ms;
  16560. };
  16561. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16562. // Windows.
  16563. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16564. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16565. // Comparing the two sizes rather than checking an absolute duration keeps
  16566. // this meaningful across build types and CI load, both of which move the
  16567. // absolute numbers by more than an order of magnitude. Four times the bytes
  16568. // costs about four times the time when parsing is linear, and about sixteen
  16569. // times when the body is buffered and rescanned.
  16570. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16571. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16572. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16573. << "ms, which suggests the body is being buffered and rescanned";
  16574. }
  16575. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16576. // A boundary can only be followed by CRLF or by "--", so anything else is
  16577. // malformed no matter what comes next. The parser must say so right away
  16578. // instead of buffering the rest of the declared body.
  16579. Server svr;
  16580. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16581. res.set_content("ok", "text/plain");
  16582. });
  16583. auto port = svr.bind_to_any_port(HOST);
  16584. thread t = thread([&] { svr.listen_after_bind(); });
  16585. auto se = detail::scope_exit([&] {
  16586. svr.stop();
  16587. t.join();
  16588. ASSERT_FALSE(svr.is_running());
  16589. });
  16590. svr.wait_until_ready();
  16591. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16592. // buffers instead of failing would still be waiting for the remaining bytes.
  16593. const std::string body = "--zzzz\r\n"
  16594. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16595. "\r\n"
  16596. "text1"
  16597. "\r\n--zzzzXX";
  16598. const std::string req = "POST /post HTTP/1.1\r\n"
  16599. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16600. "Content-Length: 1048576\r\n"
  16601. "\r\n" +
  16602. body;
  16603. std::string response;
  16604. ASSERT_TRUE(send_request(3, req, &response, port));
  16605. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16606. EXPECT_EQ("400", response.substr(9, 3));
  16607. }
  16608. // Posts a multipart body split into two writes, so that the server sees the
  16609. // split at whatever offset the caller chose, and expects the single "text1"
  16610. // field to come through.
  16611. static void expect_split_multipart_ok(const std::string &body1,
  16612. const std::string &body2) {
  16613. auto handled = false;
  16614. Server svr;
  16615. svr.Post("/post", [&](const Request &req, Response &) {
  16616. EXPECT_EQ(1u, req.form.fields.size());
  16617. EXPECT_EQ("text1", req.form.get_field("text1"));
  16618. handled = true;
  16619. });
  16620. auto port = svr.bind_to_any_port(HOST);
  16621. thread t = thread([&] { svr.listen_after_bind(); });
  16622. auto se = detail::scope_exit([&] {
  16623. svr.stop();
  16624. t.join();
  16625. ASSERT_FALSE(svr.is_running());
  16626. ASSERT_TRUE(handled);
  16627. });
  16628. svr.wait_until_ready();
  16629. // "Connection: close" makes the server close once it has answered, so the
  16630. // response drain ends immediately instead of idling until the read timeout.
  16631. const std::string head =
  16632. "POST /post HTTP/1.1\r\n"
  16633. "Host: localhost\r\n"
  16634. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16635. "Connection: close\r\n"
  16636. "Content-Length: " +
  16637. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16638. std::string response;
  16639. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16640. ASSERT_GE(response.size(), 12u) << "no response";
  16641. EXPECT_EQ("200", response.substr(9, 3));
  16642. }
  16643. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16644. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16645. // ignored, including when it does not arrive in the same read as the
  16646. // close-delimiter itself.
  16647. expect_split_multipart_ok("--zzzz\r\n"
  16648. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16649. "\r\n"
  16650. "text1"
  16651. "\r\n--zzzz--",
  16652. "\r\nthis epilogue must be ignored\r\n");
  16653. }
  16654. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16655. // The initial boundary may be preceded by a preamble of any length and may
  16656. // straddle a read boundary. Discarding data while waiting for it must not
  16657. // throw away a partial boundary sitting at the end of the buffer.
  16658. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16659. "zz\r\n"
  16660. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16661. "\r\n"
  16662. "text1"
  16663. "\r\n--zzzz--\r\n");
  16664. }
  16665. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16666. // The received boundary was only checked for being non-empty, so it could be
  16667. // as long as a header is allowed to be. The parser scans the body for
  16668. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16669. // costs a nearly full comparison at nearly every position, making the
  16670. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16671. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16672. Server svr;
  16673. svr.Post("/post", [](const Request &req, Response &res) {
  16674. EXPECT_EQ(1u, req.form.fields.size());
  16675. EXPECT_EQ("text1", req.form.get_field("text1"));
  16676. res.set_content("ok", "text/plain");
  16677. });
  16678. auto port = svr.bind_to_any_port(HOST);
  16679. thread t = thread([&] { svr.listen_after_bind(); });
  16680. auto se = detail::scope_exit([&] {
  16681. svr.stop();
  16682. t.join();
  16683. ASSERT_FALSE(svr.is_running());
  16684. });
  16685. svr.wait_until_ready();
  16686. Client cli(HOST, port);
  16687. auto post_with_boundary_of_length = [&](size_t len) {
  16688. const std::string boundary(len, 'a');
  16689. const std::string body =
  16690. "--" + boundary +
  16691. "\r\n"
  16692. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16693. "\r\n"
  16694. "text1"
  16695. "\r\n--" +
  16696. boundary + "--\r\n";
  16697. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16698. };
  16699. auto res = post_with_boundary_of_length(70);
  16700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16701. EXPECT_EQ(StatusCode::OK_200, res->status);
  16702. res = post_with_boundary_of_length(71);
  16703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16704. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16705. }
  16706. TEST(MakeFileBodyTest, Basic) {
  16707. const std::string file_content(4096, 'Z');
  16708. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16709. {
  16710. std::ofstream ofs(tmp_path, std::ios::binary);
  16711. ofs.write(file_content.data(),
  16712. static_cast<std::streamsize>(file_content.size()));
  16713. }
  16714. auto handled = false;
  16715. Server svr;
  16716. svr.Post("/upload", [&](const Request &req, Response &res) {
  16717. EXPECT_EQ(file_content, req.body);
  16718. handled = true;
  16719. res.status = StatusCode::OK_200;
  16720. });
  16721. auto port = svr.bind_to_any_port(HOST);
  16722. auto t = thread([&] { svr.listen_after_bind(); });
  16723. auto se = detail::scope_exit([&] {
  16724. svr.stop();
  16725. t.join();
  16726. ASSERT_FALSE(svr.is_running());
  16727. ASSERT_TRUE(handled);
  16728. std::remove(tmp_path.c_str());
  16729. });
  16730. svr.wait_until_ready();
  16731. auto fb = make_file_body(tmp_path);
  16732. ASSERT_GT(fb.first, 0u);
  16733. Client cli(HOST, port);
  16734. auto res =
  16735. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16737. EXPECT_EQ(StatusCode::OK_200, res->status);
  16738. }
  16739. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16740. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16741. {
  16742. std::ofstream ofs(path, std::ios::binary);
  16743. const std::string content(100, 'A');
  16744. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16745. }
  16746. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16747. auto body = make_file_body(path);
  16748. ASSERT_EQ(100u, body.first);
  16749. ASSERT_TRUE(static_cast<bool>(body.second));
  16750. // Rewritten shorter after its length was measured - and, on a server, after
  16751. // that length has already gone out as Content-Length.
  16752. {
  16753. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16754. const std::string content(10, 'A');
  16755. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16756. }
  16757. std::string written;
  16758. DataSink sink;
  16759. sink.write = [&](const char *d, size_t l) {
  16760. written.append(d, l);
  16761. return true;
  16762. };
  16763. // The provider has to report failure. write_content_with_progress() advances
  16764. // its offset only by what was written, so a provider that returns true
  16765. // without completing the length it promised is called again straight away,
  16766. // and again.
  16767. EXPECT_FALSE(body.second(0, body.first, sink));
  16768. EXPECT_EQ(std::string(10, 'A'), written);
  16769. }
  16770. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16771. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16772. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16773. {
  16774. std::ofstream ofs(path, std::ios::binary);
  16775. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16776. }
  16777. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16778. auto body = make_file_body(path);
  16779. ASSERT_EQ(content.size(), body.first);
  16780. ASSERT_TRUE(static_cast<bool>(body.second));
  16781. std::string written;
  16782. DataSink sink;
  16783. sink.write = [&](const char *d, size_t l) {
  16784. written.append(d, l);
  16785. return true;
  16786. };
  16787. EXPECT_TRUE(body.second(0, body.first, sink));
  16788. EXPECT_EQ(content, written);
  16789. }
  16790. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16791. static constexpr unsigned int number_of_tasks{1000000};
  16792. std::atomic_uint count{0};
  16793. std::unique_ptr<TaskQueue> task_queue{
  16794. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16795. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16796. auto queued = task_queue->enqueue(
  16797. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16798. EXPECT_TRUE(queued);
  16799. }
  16800. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16801. task_queue->shutdown();
  16802. #else
  16803. EXPECT_NO_THROW(task_queue->shutdown());
  16804. #endif
  16805. EXPECT_EQ(number_of_tasks, count.load());
  16806. }
  16807. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16808. static constexpr unsigned int number_of_tasks{1000000};
  16809. static constexpr unsigned int qlimit{2};
  16810. unsigned int queued_count{0};
  16811. std::atomic_uint count{0};
  16812. std::unique_ptr<TaskQueue> task_queue{
  16813. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16814. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16815. if (task_queue->enqueue(
  16816. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16817. queued_count++;
  16818. }
  16819. }
  16820. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16821. task_queue->shutdown();
  16822. #else
  16823. EXPECT_NO_THROW(task_queue->shutdown());
  16824. #endif
  16825. EXPECT_EQ(queued_count, count.load());
  16826. EXPECT_TRUE(queued_count <= number_of_tasks);
  16827. EXPECT_TRUE(queued_count >= qlimit);
  16828. }
  16829. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16830. // Use a short idle timeout so a dynamic thread spawns, times out and
  16831. // exits during the test, and the pool keeps working afterwards.
  16832. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16833. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16834. /*idle_timeout_sec=*/1}};
  16835. std::atomic_uint count{0};
  16836. std::condition_variable cv;
  16837. std::mutex mtx;
  16838. bool release = false;
  16839. // Block the base thread so the second task spawns a dynamic thread.
  16840. EXPECT_TRUE(task_queue->enqueue([&] {
  16841. std::unique_lock<std::mutex> lock(mtx);
  16842. while (!release) {
  16843. cv.wait(lock);
  16844. }
  16845. count++;
  16846. }));
  16847. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16848. // Let the dynamic thread finish its task and exceed the idle timeout.
  16849. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16850. {
  16851. std::unique_lock<std::mutex> lock(mtx);
  16852. release = true;
  16853. }
  16854. cv.notify_all();
  16855. // The pool must still accept and run tasks after the dynamic thread exited.
  16856. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16857. task_queue->shutdown();
  16858. EXPECT_EQ(3u, count.load());
  16859. }
  16860. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16861. static constexpr size_t number_of_tasks{32};
  16862. std::unique_ptr<TaskQueue> task_queue{
  16863. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16864. // Let the base threads go idle so the burst below finds them waiting.
  16865. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16866. std::mutex mtx;
  16867. std::condition_variable cv;
  16868. size_t running = 0;
  16869. bool release = false;
  16870. for (size_t i = 0; i < number_of_tasks; i++) {
  16871. EXPECT_TRUE(task_queue->enqueue([&] {
  16872. std::unique_lock<std::mutex> lock(mtx);
  16873. running++;
  16874. cv.notify_all();
  16875. cv.wait(lock, [&] { return release; });
  16876. }));
  16877. }
  16878. {
  16879. std::unique_lock<std::mutex> lock(mtx);
  16880. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16881. [&] { return running == number_of_tasks; }));
  16882. release = true;
  16883. }
  16884. cv.notify_all();
  16885. task_queue->shutdown();
  16886. }
  16887. TEST(TaskQueueTest, MaxQueuedRequests) {
  16888. static constexpr unsigned int qlimit{3};
  16889. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16890. std::condition_variable sem_cv;
  16891. std::mutex sem_mtx;
  16892. int credits = 0;
  16893. bool queued;
  16894. /* Fill up the queue with tasks that will block until we give them credits to
  16895. * complete. */
  16896. for (unsigned int n = 0; n <= qlimit;) {
  16897. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16898. std::unique_lock<std::mutex> lock(sem_mtx);
  16899. while (credits <= 0) {
  16900. sem_cv.wait(lock);
  16901. }
  16902. /* Consume the credit and signal the test code if they are all gone. */
  16903. if (--credits == 0) { sem_cv.notify_one(); }
  16904. });
  16905. if (n < qlimit) {
  16906. /* The first qlimit enqueues must succeed. */
  16907. EXPECT_TRUE(queued);
  16908. } else {
  16909. /* The last one will succeed only when the worker thread
  16910. * starts and dequeues the first blocking task. Although
  16911. * not necessary for the correctness of this test, we sleep for
  16912. * a short while to avoid busy waiting. */
  16913. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16914. }
  16915. if (queued) { n++; }
  16916. }
  16917. /* Further enqueues must fail since the queue is full. */
  16918. for (auto i = 0; i < 4; i++) {
  16919. queued = task_queue->enqueue([] {});
  16920. EXPECT_FALSE(queued);
  16921. }
  16922. /* Give the credits to allow the previous tasks to complete. */
  16923. {
  16924. std::unique_lock<std::mutex> lock(sem_mtx);
  16925. credits += qlimit + 1;
  16926. }
  16927. sem_cv.notify_all();
  16928. /* Wait for all the credits to be consumed. */
  16929. {
  16930. std::unique_lock<std::mutex> lock(sem_mtx);
  16931. while (credits > 0) {
  16932. sem_cv.wait(lock);
  16933. }
  16934. }
  16935. /* Check that we are able again to enqueue at least qlimit tasks. */
  16936. for (unsigned int i = 0; i < qlimit; i++) {
  16937. queued = task_queue->enqueue([] {});
  16938. EXPECT_TRUE(queued);
  16939. }
  16940. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16941. task_queue->shutdown();
  16942. #else
  16943. EXPECT_NO_THROW(task_queue->shutdown());
  16944. #endif
  16945. }
  16946. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16947. Server svr;
  16948. std::string method;
  16949. std::string body;
  16950. auto has_content_length = false;
  16951. auto has_transfer_encoding = false;
  16952. std::atomic<int> bad_requests{0};
  16953. // Leftover body bytes get parsed as a malformed request and answered with
  16954. // 400
  16955. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16956. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16957. });
  16958. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16959. res.set_redirect("/down", StatusCode::SeeOther_303);
  16960. });
  16961. svr.Get("/down", [&](const Request &req, Response &res) {
  16962. method = req.method;
  16963. body = req.body;
  16964. has_content_length = req.has_header("Content-Length");
  16965. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16966. res.set_content("ok", "text/plain");
  16967. });
  16968. auto port = svr.bind_to_any_port(HOST);
  16969. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. thread.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. });
  16975. svr.wait_until_ready();
  16976. const std::string payload = "SECRET-BODY";
  16977. auto check = [&](Client &cli, const Result &res) {
  16978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16979. EXPECT_EQ(StatusCode::OK_200, res->status);
  16980. EXPECT_EQ("ok", res->body);
  16981. EXPECT_EQ("GET", method);
  16982. EXPECT_TRUE(body.empty());
  16983. EXPECT_FALSE(has_content_length);
  16984. EXPECT_FALSE(has_transfer_encoding);
  16985. // Nothing of the original body may be left on the connection
  16986. auto res2 = cli.Get("/down");
  16987. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16988. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16989. EXPECT_EQ("ok", res2->body);
  16990. EXPECT_EQ(0, bad_requests);
  16991. };
  16992. // With content length
  16993. {
  16994. Client cli(HOST, port);
  16995. cli.set_keep_alive(true);
  16996. cli.set_follow_location(true);
  16997. auto res = cli.Post(
  16998. "/up", payload.size(),
  16999. [&](size_t offset, size_t length, DataSink &sink) {
  17000. return sink.write(payload.data() + offset, length);
  17001. },
  17002. "text/plain");
  17003. check(cli, res);
  17004. }
  17005. // Without content length (chunked)
  17006. {
  17007. Client cli(HOST, port);
  17008. cli.set_keep_alive(true);
  17009. cli.set_follow_location(true);
  17010. auto res = cli.Post(
  17011. "/up",
  17012. [&](size_t /*offset*/, DataSink &sink) {
  17013. sink.write(payload.data(), payload.size());
  17014. sink.done();
  17015. return true;
  17016. },
  17017. "text/plain");
  17018. check(cli, res);
  17019. }
  17020. }
  17021. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17022. Server svr;
  17023. std::string target;
  17024. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17025. // Echo the still-encoded name back in the Location
  17026. const std::string prefix = "/start/";
  17027. res.status = StatusCode::Found_302;
  17028. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17029. });
  17030. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17031. target = req.target;
  17032. res.set_content("ok", "text/plain");
  17033. });
  17034. auto port = svr.bind_to_any_port(HOST);
  17035. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17036. auto se = detail::scope_exit([&] {
  17037. svr.stop();
  17038. thread.join();
  17039. ASSERT_FALSE(svr.is_running());
  17040. });
  17041. svr.wait_until_ready();
  17042. // Decoding the Location path would turn the first four into a path
  17043. // separator, a query delimiter, a fragment delimiter and a different
  17044. // percent-encoded octet. The rest must keep reaching the server as they are.
  17045. const std::vector<std::string> names = {
  17046. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17047. };
  17048. for (auto path_encode : {true, false}) {
  17049. Client cli(HOST, port);
  17050. cli.set_follow_location(true);
  17051. cli.set_path_encode(path_encode);
  17052. for (const auto &name : names) {
  17053. target.clear();
  17054. auto res = cli.Get("/start/" + name);
  17055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17056. EXPECT_EQ(StatusCode::OK_200, res->status);
  17057. EXPECT_EQ("/dest/" + name, target);
  17058. }
  17059. }
  17060. }
  17061. TEST(RedirectTest, NotModifiedIsReturned) {
  17062. Server svr;
  17063. svr.Get("/cached", [](const Request &, Response &res) {
  17064. res.status = StatusCode::NotModified_304;
  17065. });
  17066. auto port = svr.bind_to_any_port(HOST);
  17067. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17068. auto se = detail::scope_exit([&] {
  17069. svr.stop();
  17070. thread.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. svr.wait_until_ready();
  17074. Client cli(HOST, port);
  17075. cli.set_follow_location(true);
  17076. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17079. }
  17080. TEST(RedirectTest, NoLocationIsReturned) {
  17081. Server svr;
  17082. svr.Get("/no-location", [](const Request &, Response &res) {
  17083. res.status = StatusCode::Found_302;
  17084. res.set_content("no location", "text/plain");
  17085. });
  17086. auto port = svr.bind_to_any_port(HOST);
  17087. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17088. auto se = detail::scope_exit([&] {
  17089. svr.stop();
  17090. thread.join();
  17091. ASSERT_FALSE(svr.is_running());
  17092. });
  17093. svr.wait_until_ready();
  17094. Client cli(HOST, port);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Get("/no-location");
  17097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17098. EXPECT_EQ(StatusCode::Found_302, res->status);
  17099. EXPECT_EQ("no location", res->body);
  17100. // The callbacks see the body of the response that is returned
  17101. auto handler_called = false;
  17102. auto progress_called = false;
  17103. std::string body;
  17104. auto res2 = cli.Get(
  17105. "/no-location",
  17106. [&](const Response &) {
  17107. handler_called = true;
  17108. return true;
  17109. },
  17110. [&](const char *data, size_t data_length) {
  17111. body.append(data, data_length);
  17112. return true;
  17113. },
  17114. [&](size_t, size_t) {
  17115. progress_called = true;
  17116. return true;
  17117. });
  17118. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17119. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17120. EXPECT_TRUE(handler_called);
  17121. EXPECT_TRUE(progress_called);
  17122. EXPECT_EQ("no location", body);
  17123. }
  17124. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17125. Server svr;
  17126. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17127. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17128. });
  17129. svr.Get("/hello", [](const Request &req, Response &res) {
  17130. res.set_content(req.get_param_value("key"), "text/plain");
  17131. });
  17132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. thread.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. });
  17138. svr.wait_until_ready();
  17139. {
  17140. Client cli(HOST, PORT);
  17141. cli.set_follow_location(true);
  17142. auto res = cli.Get("/");
  17143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17144. EXPECT_EQ(StatusCode::OK_200, res->status);
  17145. EXPECT_EQ("val&key2=val2", res->body);
  17146. }
  17147. }
  17148. #endif
  17149. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17150. Server svr;
  17151. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17152. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17153. });
  17154. svr.Get("/hello", [](const Request &req, Response &res) {
  17155. res.set_content(req.get_param_value("key"), "text/plain");
  17156. });
  17157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17158. auto se = detail::scope_exit([&] {
  17159. svr.stop();
  17160. thread.join();
  17161. ASSERT_FALSE(svr.is_running());
  17162. });
  17163. svr.wait_until_ready();
  17164. {
  17165. Client cli(HOST, PORT);
  17166. cli.set_follow_location(true);
  17167. auto res = cli.Get("/");
  17168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17169. EXPECT_EQ(StatusCode::OK_200, res->status);
  17170. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17171. }
  17172. }
  17173. TEST(RedirectTest, RedirectWithPlusInPath) {
  17174. Server svr;
  17175. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17176. res.set_redirect("/a+b");
  17177. });
  17178. // Route pattern uses regex; escape + as \\+
  17179. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17180. res.set_content(req.path, "text/plain");
  17181. });
  17182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17183. auto se = detail::scope_exit([&] {
  17184. svr.stop();
  17185. thread.join();
  17186. ASSERT_FALSE(svr.is_running());
  17187. });
  17188. svr.wait_until_ready();
  17189. {
  17190. Client cli(HOST, PORT);
  17191. cli.set_follow_location(true);
  17192. auto res = cli.Get("/");
  17193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17194. EXPECT_EQ(StatusCode::OK_200, res->status);
  17195. EXPECT_EQ("/a+b", res->body);
  17196. }
  17197. }
  17198. TEST(RedirectTest, ResolveRelativeLocation) {
  17199. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17200. const std::vector<std::pair<std::string, std::string>> cases = {
  17201. {"g", "/b/c/g"},
  17202. {"./g", "/b/c/g"},
  17203. {"g/", "/b/c/g/"},
  17204. {"?y", "/b/c/d;p?y"},
  17205. {"g?y", "/b/c/g?y"},
  17206. {"#s", "/b/c/d;p?q#s"},
  17207. {"g#s", "/b/c/g#s"},
  17208. {"g?y#s", "/b/c/g?y#s"},
  17209. {";x", "/b/c/;x"},
  17210. {"g;x", "/b/c/g;x"},
  17211. {".", "/b/c/"},
  17212. {"./", "/b/c/"},
  17213. {"..", "/b/"},
  17214. {"../", "/b/"},
  17215. {"../g", "/b/g"},
  17216. {"../..", "/"},
  17217. {"../../", "/"},
  17218. {"../../g", "/g"},
  17219. {"../../../g", "/g"},
  17220. {"g.", "/b/c/g."},
  17221. {".g", "/b/c/.g"},
  17222. {"g..", "/b/c/g.."},
  17223. {"..g", "/b/c/..g"},
  17224. {"./../g", "/b/g"},
  17225. {"./g/.", "/b/c/g/"},
  17226. {"g/./h", "/b/c/g/h"},
  17227. {"g/../h", "/b/c/h"},
  17228. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17229. {"g;x=1/../y", "/b/c/y"},
  17230. {"g?y/./x", "/b/c/g?y/./x"},
  17231. {"g#s/../x", "/b/c/g#s/../x"},
  17232. // Not relative-path references, so left for parse_url.
  17233. {"/g", "/g"},
  17234. {"//g", "//g"},
  17235. {"http://g/x", "http://g/x"},
  17236. {"g:h", "g:h"},
  17237. };
  17238. for (const auto &c : cases) {
  17239. EXPECT_EQ(c.second,
  17240. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17241. << c.first;
  17242. }
  17243. }
  17244. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17245. Server svr;
  17246. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17247. res.set_redirect(req.get_param_value("to"));
  17248. });
  17249. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17250. res.set_content(req.target, "text/plain");
  17251. });
  17252. svr.Get("/other", [](const Request &req, Response &res) {
  17253. res.set_content(req.target, "text/plain");
  17254. });
  17255. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17256. auto se = detail::scope_exit([&] {
  17257. svr.stop();
  17258. thread.join();
  17259. ASSERT_FALSE(svr.is_running());
  17260. });
  17261. svr.wait_until_ready();
  17262. const std::vector<std::pair<std::string, std::string>> cases = {
  17263. {"next", "/dir/next"},
  17264. {"./next?x=1", "/dir/next?x=1"},
  17265. {"../other", "/other"},
  17266. };
  17267. for (const auto &c : cases) {
  17268. Client cli(HOST, PORT);
  17269. cli.set_follow_location(true);
  17270. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17271. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17272. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17273. EXPECT_EQ(c.second, res->body) << c.first;
  17274. }
  17275. }
  17276. #ifdef CPPHTTPLIB_SSL_ENABLED
  17277. TEST(RedirectTest, Issue2185_Online) {
  17278. SSLClient client("github.com");
  17279. client.set_follow_location(true);
  17280. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17281. "Coollab-Windows.zip");
  17282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17283. EXPECT_EQ(StatusCode::OK_200, res->status);
  17284. EXPECT_EQ(9920427U, res->body.size());
  17285. }
  17286. #endif
  17287. TEST(VulnerabilityTest, CRLFInjection) {
  17288. Server svr;
  17289. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17290. res.set_content("Hello 1", "text/plain");
  17291. });
  17292. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17293. res.set_content("Hello 2", "text/plain");
  17294. });
  17295. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17296. res.set_content("Hello 3", "text/plain");
  17297. });
  17298. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17299. res.set_content("Hello 4", "text/plain");
  17300. });
  17301. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17302. for (const auto &x : req.headers) {
  17303. auto key = x.first;
  17304. EXPECT_STRNE("evil", key.c_str());
  17305. }
  17306. });
  17307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17308. auto se = detail::scope_exit([&] {
  17309. svr.stop();
  17310. thread.join();
  17311. ASSERT_FALSE(svr.is_running());
  17312. });
  17313. svr.wait_until_ready();
  17314. {
  17315. Client cli(HOST, PORT);
  17316. cli.Post("/test1", "A=B",
  17317. "application/x-www-form-urlencoded\r\nevil: hello1");
  17318. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17319. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17320. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17321. }
  17322. }
  17323. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17324. auto server_thread = std::thread([] {
  17325. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17326. default_socket_options(srv);
  17327. sockaddr_in addr{};
  17328. addr.sin_family = AF_INET;
  17329. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17330. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17331. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17332. ::listen(srv, 1);
  17333. sockaddr_in cli_addr{};
  17334. socklen_t cli_len = sizeof(cli_addr);
  17335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17336. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17337. std::string buf_all;
  17338. char buf[2048];
  17339. ssize_t n;
  17340. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17341. buf_all.append(buf, static_cast<size_t>(n));
  17342. size_t pos;
  17343. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17344. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17345. auto e = request_block.find("\r\n");
  17346. if (e != std::string::npos) {
  17347. auto request_line = request_block.substr(0, e);
  17348. std::string msg =
  17349. "CRLF injection detected in request line: '" + request_line + "'";
  17350. EXPECT_FALSE(true) << msg;
  17351. }
  17352. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17353. ::send(cli,
  17354. #ifdef _WIN32
  17355. static_cast<const char *>(resp.c_str()),
  17356. static_cast<int>(resp.size()),
  17357. #else
  17358. resp.c_str(), resp.size(),
  17359. #endif
  17360. 0);
  17361. buf_all.erase(0, pos + 4);
  17362. }
  17363. }
  17364. detail::close_socket(cli);
  17365. detail::close_socket(srv);
  17366. });
  17367. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17368. auto cli = Client("127.0.0.1", PORT + 1);
  17369. auto headers = Headers{
  17370. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17371. {"Connection", "keep-alive"}};
  17372. auto res = cli.Get("/hi", headers);
  17373. EXPECT_FALSE(res);
  17374. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17375. server_thread.join();
  17376. }
  17377. // A request rejected before any byte reaches the socket must fail right away
  17378. // instead of waiting for a response the server will never send.
  17379. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17380. // The kernel completes the TCP handshake from the listen backlog, so the
  17381. // client connects, but nothing ever reads, responds or closes.
  17382. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17383. default_socket_options(srv);
  17384. sockaddr_in addr{};
  17385. addr.sin_family = AF_INET;
  17386. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17388. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17389. ASSERT_EQ(0, ::listen(srv, 8));
  17390. auto cli = Client("127.0.0.1", PORT + 1);
  17391. cli.set_read_timeout(10, 0);
  17392. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17393. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17394. std::chrono::steady_clock::now() - start)
  17395. .count();
  17396. };
  17397. {
  17398. Request req;
  17399. req.method = "GE T";
  17400. req.path = "/";
  17401. auto start = std::chrono::steady_clock::now();
  17402. auto res = cli.send(req);
  17403. EXPECT_FALSE(res);
  17404. EXPECT_EQ(Error::Write, res.error());
  17405. EXPECT_LT(elapsed_ms(start), 1000);
  17406. }
  17407. {
  17408. auto start = std::chrono::steady_clock::now();
  17409. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17410. EXPECT_FALSE(res);
  17411. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17412. EXPECT_LT(elapsed_ms(start), 1000);
  17413. }
  17414. EXPECT_FALSE(cli.is_socket_open());
  17415. detail::close_socket(srv);
  17416. }
  17417. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17419. default_socket_options(srv);
  17420. sockaddr_in addr{};
  17421. addr.sin_family = AF_INET;
  17422. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17423. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17424. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17425. ASSERT_EQ(0, ::listen(srv, 1));
  17426. std::string received;
  17427. auto server_thread = std::thread([&] {
  17428. auto sock = ::accept(srv, nullptr, nullptr);
  17429. if (sock == INVALID_SOCKET) { return; }
  17430. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17431. char buf[2048];
  17432. ssize_t n;
  17433. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17434. received.append(buf, static_cast<size_t>(n));
  17435. }
  17436. detail::close_socket(sock);
  17437. });
  17438. {
  17439. auto cli = Client("127.0.0.1", PORT + 1);
  17440. // "Z" sorts after the default headers, so writing straight to the socket
  17441. // would have sent the request line and those headers before the rejection.
  17442. auto handle =
  17443. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17444. EXPECT_FALSE(handle.is_valid());
  17445. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17446. }
  17447. server_thread.join();
  17448. detail::close_socket(srv);
  17449. EXPECT_TRUE(received.empty()) << received;
  17450. }
  17451. TEST(PathParamsTest, StaticMatch) {
  17452. const auto pattern = "/users/all";
  17453. detail::PathParamsMatcher matcher(pattern);
  17454. Request request;
  17455. request.path = "/users/all";
  17456. ASSERT_TRUE(matcher.match(request));
  17457. std::unordered_map<std::string, std::string> expected_params = {};
  17458. EXPECT_EQ(request.path_params, expected_params);
  17459. }
  17460. TEST(PathParamsTest, StaticMismatch) {
  17461. const auto pattern = "/users/all";
  17462. detail::PathParamsMatcher matcher(pattern);
  17463. Request request;
  17464. request.path = "/users/1";
  17465. ASSERT_FALSE(matcher.match(request));
  17466. }
  17467. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17468. const auto pattern = "/users/:id/subscriptions";
  17469. detail::PathParamsMatcher matcher(pattern);
  17470. Request request;
  17471. request.path = "/users/42/subscriptions";
  17472. ASSERT_TRUE(matcher.match(request));
  17473. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17474. EXPECT_EQ(request.path_params, expected_params);
  17475. }
  17476. TEST(PathParamsTest, SingleParamInTheEnd) {
  17477. const auto pattern = "/users/:id";
  17478. detail::PathParamsMatcher matcher(pattern);
  17479. Request request;
  17480. request.path = "/users/24";
  17481. ASSERT_TRUE(matcher.match(request));
  17482. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17483. EXPECT_EQ(request.path_params, expected_params);
  17484. }
  17485. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17486. const auto pattern = "/users/:id/";
  17487. detail::PathParamsMatcher matcher(pattern);
  17488. Request request;
  17489. request.path = "/users/42/";
  17490. ASSERT_TRUE(matcher.match(request));
  17491. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17492. EXPECT_EQ(request.path_params, expected_params);
  17493. }
  17494. TEST(PathParamsTest, EmptyParam) {
  17495. const auto pattern = "/users/:id/";
  17496. detail::PathParamsMatcher matcher(pattern);
  17497. Request request;
  17498. request.path = "/users//";
  17499. ASSERT_TRUE(matcher.match(request));
  17500. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17501. EXPECT_EQ(request.path_params, expected_params);
  17502. }
  17503. TEST(PathParamsTest, FragmentMismatch) {
  17504. const auto pattern = "/users/:id/";
  17505. detail::PathParamsMatcher matcher(pattern);
  17506. Request request;
  17507. request.path = "/admins/24/";
  17508. ASSERT_FALSE(matcher.match(request));
  17509. }
  17510. TEST(PathParamsTest, ExtraFragments) {
  17511. const auto pattern = "/users/:id";
  17512. detail::PathParamsMatcher matcher(pattern);
  17513. Request request;
  17514. request.path = "/users/42/subscriptions";
  17515. ASSERT_FALSE(matcher.match(request));
  17516. }
  17517. TEST(PathParamsTest, MissingTrailingParam) {
  17518. const auto pattern = "/users/:id";
  17519. detail::PathParamsMatcher matcher(pattern);
  17520. Request request;
  17521. request.path = "/users";
  17522. ASSERT_FALSE(matcher.match(request));
  17523. }
  17524. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17525. const auto pattern = "/users/:id/subscriptions";
  17526. detail::PathParamsMatcher matcher(pattern);
  17527. Request request;
  17528. request.path = "/users/subscriptions";
  17529. ASSERT_FALSE(matcher.match(request));
  17530. }
  17531. TEST(PathParamsTest, MultipleParams) {
  17532. const auto pattern = "/users/:userid/subscriptions/:subid";
  17533. detail::PathParamsMatcher matcher(pattern);
  17534. Request request;
  17535. request.path = "/users/42/subscriptions/2";
  17536. ASSERT_TRUE(matcher.match(request));
  17537. std::unordered_map<std::string, std::string> expected_params = {
  17538. {"userid", "42"}, {"subid", "2"}};
  17539. EXPECT_EQ(request.path_params, expected_params);
  17540. }
  17541. TEST(PathParamsTest, SequenceOfParams) {
  17542. const auto pattern = "/values/:x/:y/:z";
  17543. detail::PathParamsMatcher matcher(pattern);
  17544. Request request;
  17545. request.path = "/values/1/2/3";
  17546. ASSERT_TRUE(matcher.match(request));
  17547. std::unordered_map<std::string, std::string> expected_params = {
  17548. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17549. EXPECT_EQ(request.path_params, expected_params);
  17550. }
  17551. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17552. const auto pattern = "/prefix:suffix";
  17553. detail::PathParamsMatcher matcher(pattern);
  17554. Request request;
  17555. request.path = "/prefix:suffix";
  17556. ASSERT_TRUE(matcher.match(request));
  17557. const std::unordered_map<std::string, std::string> expected_params = {};
  17558. EXPECT_EQ(request.path_params, expected_params);
  17559. }
  17560. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17561. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17562. // calling thread's stack on a long enough path for a quantified pattern;
  17563. // RegexMatcher must refuse to run regex matching on paths beyond
  17564. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17565. detail::RegexMatcher matcher("/files/(.*)");
  17566. Request within_limit;
  17567. within_limit.path = "/files/" + std::string(10, 'A');
  17568. EXPECT_TRUE(matcher.match(within_limit));
  17569. Request over_limit;
  17570. over_limit.path =
  17571. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17572. EXPECT_FALSE(matcher.match(over_limit));
  17573. }
  17574. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17575. Server svr;
  17576. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17577. res.set_content("ok", "text/plain");
  17578. });
  17579. auto port = svr.bind_to_any_port(HOST);
  17580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17581. auto se = detail::scope_exit([&] {
  17582. svr.stop();
  17583. thread.join();
  17584. ASSERT_FALSE(svr.is_running());
  17585. });
  17586. svr.wait_until_ready();
  17587. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17588. // request URI limit; this used to be able to crash the process.
  17589. std::string path =
  17590. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17591. std::string req = "GET " + path +
  17592. " HTTP/1.1\r\n"
  17593. "Host: " +
  17594. std::string(HOST) + ":" + std::to_string(port) +
  17595. "\r\n"
  17596. "Connection: close\r\n"
  17597. "\r\n";
  17598. std::string response;
  17599. ASSERT_TRUE(send_request(5, req, &response, port));
  17600. EXPECT_NE(std::string::npos, response.find("404"));
  17601. }
  17602. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17603. Server svr;
  17604. auto handler = [](const Request & /*req*/, Response &res) {
  17605. res.set_content("hit", "text/plain");
  17606. };
  17607. // No regex metacharacter, so this one is compared literally
  17608. svr.Get("/literal/route", handler);
  17609. // '.' is a regex metacharacter, so this one must keep regex semantics
  17610. svr.Get("/a.c", handler);
  17611. auto port = svr.bind_to_any_port(HOST);
  17612. std::thread t([&]() { svr.listen_after_bind(); });
  17613. auto se = detail::scope_exit([&] {
  17614. svr.stop();
  17615. t.join();
  17616. ASSERT_FALSE(svr.is_running());
  17617. });
  17618. svr.wait_until_ready();
  17619. Client cli(HOST, port);
  17620. struct {
  17621. const char *path;
  17622. int status;
  17623. } cases[] = {
  17624. {"/literal/route", StatusCode::OK_200},
  17625. {"/literal/routes", StatusCode::NotFound_404},
  17626. {"/literal/rout", StatusCode::NotFound_404},
  17627. {"/abc", StatusCode::OK_200},
  17628. {"/a.c", StatusCode::OK_200},
  17629. };
  17630. for (const auto &x : cases) {
  17631. auto res = cli.Get(x.path);
  17632. ASSERT_TRUE(res) << x.path;
  17633. EXPECT_EQ(x.status, res->status) << x.path;
  17634. }
  17635. }
  17636. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17637. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17638. // from exhausting the stack, so it must only constrain routes that actually
  17639. // run a regular expression. A literal route is matched by comparison and
  17640. // stays usable at any length.
  17641. Server svr;
  17642. const std::string pattern =
  17643. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17644. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17645. res.set_content("hit", "text/plain");
  17646. });
  17647. auto port = svr.bind_to_any_port(HOST);
  17648. std::thread t([&]() { svr.listen_after_bind(); });
  17649. auto se = detail::scope_exit([&] {
  17650. svr.stop();
  17651. t.join();
  17652. ASSERT_FALSE(svr.is_running());
  17653. });
  17654. svr.wait_until_ready();
  17655. Client cli(HOST, port);
  17656. auto res = cli.Get(pattern);
  17657. ASSERT_TRUE(res);
  17658. EXPECT_EQ(StatusCode::OK_200, res->status);
  17659. }
  17660. TEST(ParseUrlTest, VariousPatterns) {
  17661. {
  17662. detail::UrlComponents uc;
  17663. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17664. EXPECT_EQ("http", uc.scheme);
  17665. EXPECT_EQ("example.com", uc.host);
  17666. EXPECT_EQ("8080", uc.port);
  17667. EXPECT_EQ("/path", uc.path);
  17668. EXPECT_EQ("?q=1", uc.query);
  17669. }
  17670. {
  17671. detail::UrlComponents uc;
  17672. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17673. EXPECT_EQ("https", uc.scheme);
  17674. EXPECT_EQ("example.com", uc.host);
  17675. EXPECT_TRUE(uc.port.empty());
  17676. EXPECT_EQ("/path", uc.path);
  17677. }
  17678. {
  17679. detail::UrlComponents uc;
  17680. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17681. EXPECT_EQ("::1", uc.host);
  17682. EXPECT_EQ("8080", uc.port);
  17683. EXPECT_EQ("/path", uc.path);
  17684. }
  17685. {
  17686. detail::UrlComponents uc;
  17687. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17688. }
  17689. {
  17690. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17691. // the path while the connection still targets the bracketed host.
  17692. detail::UrlComponents uc;
  17693. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17694. }
  17695. {
  17696. detail::UrlComponents uc;
  17697. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17698. }
  17699. {
  17700. detail::UrlComponents uc;
  17701. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17702. EXPECT_EQ("::1", uc.host);
  17703. EXPECT_TRUE(uc.port.empty());
  17704. EXPECT_EQ("/path", uc.path);
  17705. }
  17706. {
  17707. detail::UrlComponents uc;
  17708. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17709. EXPECT_TRUE(uc.scheme.empty());
  17710. EXPECT_EQ("example.com", uc.host);
  17711. EXPECT_EQ("/path", uc.path);
  17712. EXPECT_EQ("?q=1", uc.query);
  17713. }
  17714. {
  17715. detail::UrlComponents uc;
  17716. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17717. EXPECT_TRUE(uc.host.empty());
  17718. EXPECT_EQ("/path", uc.path);
  17719. EXPECT_EQ("?q=1", uc.query);
  17720. }
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17724. EXPECT_EQ("example.com", uc.host);
  17725. EXPECT_EQ("8080", uc.port);
  17726. }
  17727. {
  17728. // Unix socket path — must not be parsed as host
  17729. detail::UrlComponents uc;
  17730. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17731. EXPECT_TRUE(uc.host.empty());
  17732. }
  17733. {
  17734. detail::UrlComponents uc;
  17735. ASSERT_TRUE(detail::parse_url("", uc));
  17736. EXPECT_TRUE(uc.host.empty());
  17737. EXPECT_TRUE(uc.path.empty());
  17738. }
  17739. {
  17740. detail::UrlComponents uc;
  17741. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17742. }
  17743. {
  17744. detail::UrlComponents uc;
  17745. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17746. }
  17747. {
  17748. // Accepted by parse_url; callers restrict to http/https
  17749. detail::UrlComponents uc;
  17750. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17751. EXPECT_EQ("ftp", uc.scheme);
  17752. }
  17753. {
  17754. detail::UrlComponents uc;
  17755. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17756. }
  17757. {
  17758. detail::UrlComponents uc;
  17759. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17760. }
  17761. }
  17762. TEST(ParseUrlTest, FragmentHandling) {
  17763. {
  17764. detail::UrlComponents uc;
  17765. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17766. EXPECT_EQ("/path", uc.path);
  17767. EXPECT_TRUE(uc.query.empty());
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17772. EXPECT_TRUE(uc.path.empty());
  17773. EXPECT_TRUE(uc.query.empty());
  17774. }
  17775. }
  17776. TEST(ParseUrlTest, UserinfoHandling) {
  17777. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17778. // parsers would see evil.com as the host.
  17779. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17780. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17781. for (auto url : urls) {
  17782. detail::UrlComponents uc;
  17783. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17784. }
  17785. }
  17786. TEST(ParseUrlTest, IPv6EdgeCases) {
  17787. {
  17788. detail::UrlComponents uc;
  17789. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17790. EXPECT_TRUE(uc.scheme.empty());
  17791. EXPECT_EQ("::1", uc.host);
  17792. EXPECT_EQ("8080", uc.port);
  17793. }
  17794. {
  17795. // Zone ID '%25' is not in [a-fA-F0-9:]
  17796. detail::UrlComponents uc;
  17797. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17798. }
  17799. }
  17800. TEST(ParseUrlTest, SchemeEdgeCases) {
  17801. {
  17802. detail::UrlComponents uc;
  17803. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17804. }
  17805. {
  17806. detail::UrlComponents uc;
  17807. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17808. }
  17809. {
  17810. detail::UrlComponents uc;
  17811. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17812. }
  17813. }
  17814. TEST(ParseUrlTest, PortEdgeCases) {
  17815. {
  17816. detail::UrlComponents uc;
  17817. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17818. EXPECT_TRUE(uc.port.empty());
  17819. EXPECT_EQ("/path", uc.path);
  17820. }
  17821. {
  17822. // parse_url accepts any port string; validation is done by parse_port
  17823. detail::UrlComponents uc;
  17824. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17825. EXPECT_EQ("abc", uc.port);
  17826. }
  17827. }
  17828. TEST(ParseUrlTest, WebSocketPatterns) {
  17829. {
  17830. detail::UrlComponents uc;
  17831. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17832. EXPECT_EQ("ws", uc.scheme);
  17833. EXPECT_EQ("echo.example.com", uc.host);
  17834. EXPECT_EQ("8080", uc.port);
  17835. EXPECT_EQ("/ws", uc.path);
  17836. }
  17837. {
  17838. detail::UrlComponents uc;
  17839. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17840. EXPECT_EQ("wss", uc.scheme);
  17841. EXPECT_EQ("echo.example.com", uc.host);
  17842. EXPECT_TRUE(uc.port.empty());
  17843. EXPECT_EQ("/ws", uc.path);
  17844. }
  17845. }
  17846. TEST(ParseUrlTest, QueryOnly) {
  17847. detail::UrlComponents uc;
  17848. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17849. EXPECT_TRUE(uc.host.empty());
  17850. EXPECT_TRUE(uc.path.empty());
  17851. EXPECT_EQ("?q=1&r=2", uc.query);
  17852. }
  17853. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17854. detail::UrlComponents uc;
  17855. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17856. EXPECT_TRUE(uc.scheme.empty());
  17857. EXPECT_EQ("example.com", uc.host);
  17858. EXPECT_EQ("443", uc.port);
  17859. EXPECT_EQ("/path", uc.path);
  17860. }
  17861. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17862. // If ipv6 regex working, regex match codepath is taken.
  17863. // else port will default to 80 in Client impl
  17864. int clientImplMagicPort = 80;
  17865. int port = 4321;
  17866. // above ports must be different to avoid false negative
  17867. EXPECT_NE(clientImplMagicPort, port);
  17868. std::string ipV6TestURL = "http://[ff06::c3]";
  17869. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17870. CLIENT_PRIVATE_KEY_FILE);
  17871. EXPECT_EQ(cli.port(), port);
  17872. }
  17873. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17874. auto file_path = "./www/dir/index.html";
  17875. auto dir_path = "./www/dir";
  17876. detail::FileStat stat_file(file_path);
  17877. EXPECT_TRUE(stat_file.is_file());
  17878. EXPECT_FALSE(stat_file.is_dir());
  17879. detail::FileStat stat_dir(dir_path);
  17880. EXPECT_FALSE(stat_dir.is_file());
  17881. EXPECT_TRUE(stat_dir.is_dir());
  17882. }
  17883. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17884. // IPv4 with default HTTP port (80)
  17885. EXPECT_EQ("example.com",
  17886. detail::make_host_and_port_string("example.com", 80, false));
  17887. // IPv4 with default HTTPS port (443)
  17888. EXPECT_EQ("example.com",
  17889. detail::make_host_and_port_string("example.com", 443, true));
  17890. // IPv4 with non-default HTTP port
  17891. EXPECT_EQ("example.com:8080",
  17892. detail::make_host_and_port_string("example.com", 8080, false));
  17893. // IPv4 with non-default HTTPS port
  17894. EXPECT_EQ("example.com:8443",
  17895. detail::make_host_and_port_string("example.com", 8443, true));
  17896. // IPv6 with default HTTP port (80)
  17897. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17898. // IPv6 with default HTTPS port (443)
  17899. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17900. // IPv6 with non-default HTTP port
  17901. EXPECT_EQ("[::1]:8080",
  17902. detail::make_host_and_port_string("::1", 8080, false));
  17903. // IPv6 with non-default HTTPS port
  17904. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17905. // IPv6 full address with default port
  17906. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17907. detail::make_host_and_port_string(
  17908. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17909. // IPv6 full address with non-default port
  17910. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17911. detail::make_host_and_port_string(
  17912. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17913. // IPv6 localhost with non-default port
  17914. EXPECT_EQ("[::1]:3000",
  17915. detail::make_host_and_port_string("::1", 3000, false));
  17916. // IPv6 with zone ID (link-local address) with default port
  17917. EXPECT_EQ("[fe80::1%eth0]",
  17918. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17919. // IPv6 with zone ID (link-local address) with non-default port
  17920. EXPECT_EQ("[fe80::1%eth0]:8080",
  17921. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17922. // Edge case: Port 443 with is_ssl=false (should add port)
  17923. EXPECT_EQ("example.com:443",
  17924. detail::make_host_and_port_string("example.com", 443, false));
  17925. // Edge case: Port 80 with is_ssl=true (should add port)
  17926. EXPECT_EQ("example.com:80",
  17927. detail::make_host_and_port_string("example.com", 80, true));
  17928. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17929. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17930. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17931. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17932. // Security fix: Already bracketed IPv6 should not get double brackets
  17933. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17934. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17935. EXPECT_EQ("[::1]:8080",
  17936. detail::make_host_and_port_string("[::1]", 8080, false));
  17937. EXPECT_EQ("[2001:db8::1]:8080",
  17938. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17939. EXPECT_EQ("[fe80::1%eth0]",
  17940. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17941. EXPECT_EQ("[fe80::1%eth0]:8080",
  17942. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17943. // Edge case: Empty host (should return as-is)
  17944. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17945. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17946. // This is a known limitation but shouldn't crash
  17947. EXPECT_EQ("[host:name]",
  17948. detail::make_host_and_port_string("host:name", 80, false));
  17949. // Port number edge cases (no validation, but should not crash)
  17950. EXPECT_EQ("example.com:0",
  17951. detail::make_host_and_port_string("example.com", 0, false));
  17952. EXPECT_EQ("example.com:-1",
  17953. detail::make_host_and_port_string("example.com", -1, false));
  17954. EXPECT_EQ("example.com:65535",
  17955. detail::make_host_and_port_string("example.com", 65535, false));
  17956. EXPECT_EQ("example.com:65536",
  17957. detail::make_host_and_port_string("example.com", 65536, false));
  17958. }
  17959. #ifdef CPPHTTPLIB_SSL_ENABLED
  17960. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17961. httplib::SSLClient cli("roblox.com", 443);
  17962. cli.set_follow_location(true);
  17963. auto res = cli.Get("/");
  17964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17965. EXPECT_EQ(StatusCode::OK_200, res->status);
  17966. }
  17967. #endif
  17968. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17969. Server svr;
  17970. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17971. EXPECT_EQ(res.status, 400);
  17972. });
  17973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17974. auto se = detail::scope_exit([&] {
  17975. svr.stop();
  17976. thread.join();
  17977. ASSERT_FALSE(svr.is_running());
  17978. });
  17979. svr.wait_until_ready();
  17980. Client cli(HOST, PORT);
  17981. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17982. }
  17983. TEST(InvalidHeaderCharsTest, is_field_name) {
  17984. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17985. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17986. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17987. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17988. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17989. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17990. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17991. EXPECT_FALSE(detail::fields::is_field_name(""));
  17992. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17993. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17994. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17995. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17996. }
  17997. TEST(InvalidHeaderCharsTest, is_field_value) {
  17998. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17999. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18000. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18001. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18002. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18003. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18004. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18005. EXPECT_TRUE(detail::fields::is_field_value(""));
  18006. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18007. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18008. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18009. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18010. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18011. }
  18012. TEST(InvalidHeaderCharsTest, OnServer) {
  18013. Server svr;
  18014. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18015. std::string header = "Not Set";
  18016. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18017. res.set_header(header, "value");
  18018. res.set_content("Page Content Page Content", "text/plain");
  18019. });
  18020. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18021. std::string header = "Not Set";
  18022. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18023. res.set_header("X-Test", header);
  18024. res.set_content("Page Content Page Content", "text/plain");
  18025. });
  18026. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18027. auto se = detail::scope_exit([&] {
  18028. svr.stop();
  18029. thread.join();
  18030. ASSERT_FALSE(svr.is_running());
  18031. });
  18032. svr.wait_until_ready();
  18033. Client cli(HOST, PORT);
  18034. {
  18035. auto res = cli.Get(
  18036. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18038. EXPECT_EQ("Page Content Page Content", res->body);
  18039. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18040. }
  18041. {
  18042. auto res = cli.Get(
  18043. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18045. EXPECT_EQ("Page Content Page Content", res->body);
  18046. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18047. }
  18048. }
  18049. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18050. auto handled = false;
  18051. Server svr;
  18052. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18053. thread t = thread([&] { svr.listen(HOST, PORT); });
  18054. auto se = detail::scope_exit([&] {
  18055. svr.stop();
  18056. t.join();
  18057. ASSERT_FALSE(svr.is_running());
  18058. ASSERT_FALSE(handled);
  18059. });
  18060. svr.wait_until_ready();
  18061. auto req = "POST /test HTTP/1.1\r\n"
  18062. "Content-Length: x\r\n"
  18063. "\r\n";
  18064. std::string response;
  18065. ASSERT_TRUE(send_request(1, req, &response));
  18066. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18067. response.substr(0, response.find("\r\n")));
  18068. }
  18069. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18070. // case-insensitive, and a server that receives a 100-continue expectation in
  18071. // an HTTP/1.0 request MUST ignore it.
  18072. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18073. std::string response;
  18074. ASSERT_TRUE(send_request(1, req, &response, port));
  18075. *got_100 = response.find("100 Continue") != std::string::npos;
  18076. }
  18077. class ExpectTokenTest : public ::testing::Test {
  18078. protected:
  18079. void SetUp() override {
  18080. svr_.Post("/p", [](const Request &, Response &res) {
  18081. res.set_content("ok", "text/plain");
  18082. });
  18083. port_ = svr_.bind_to_any_port(HOST);
  18084. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18085. svr_.wait_until_ready();
  18086. }
  18087. void TearDown() override {
  18088. svr_.stop();
  18089. if (thread_.joinable()) { thread_.join(); }
  18090. }
  18091. std::string request(const char *version, const char *expect_value) const {
  18092. return std::string("POST /p ") + version +
  18093. "\r\n"
  18094. "Host: localhost\r\n"
  18095. "Content-Length: 2\r\n"
  18096. "Connection: close\r\n"
  18097. "Expect: " +
  18098. expect_value +
  18099. "\r\n"
  18100. "\r\n"
  18101. "hi";
  18102. }
  18103. Server svr_;
  18104. int port_ = 0;
  18105. thread thread_;
  18106. };
  18107. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18108. bool got_100 = false;
  18109. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18110. EXPECT_TRUE(got_100);
  18111. }
  18112. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18113. bool got_100 = true;
  18114. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18115. EXPECT_FALSE(got_100);
  18116. }
  18117. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18118. bool got_100 = false;
  18119. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18120. EXPECT_TRUE(got_100);
  18121. }
  18122. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18123. bool got_100 = false;
  18124. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18125. EXPECT_TRUE(got_100);
  18126. }
  18127. // `100 Continue` is sent only when the server starts reading the body, so a
  18128. // request rejected before that never invites the client to send it. The
  18129. // requests below carry the expectation but withhold the body, as a client
  18130. // waiting for `100 Continue` would.
  18131. // A POST that expects `100 Continue` and withholds its two-byte body.
  18132. static std::string expect_headers_only(const std::string &path) {
  18133. return "POST " + path +
  18134. " HTTP/1.1\r\n"
  18135. "Host: localhost\r\n"
  18136. "Content-Length: 2\r\n"
  18137. "Expect: 100-continue\r\n"
  18138. "\r\n";
  18139. }
  18140. class ExpectLazyContinueTest : public ::testing::Test {
  18141. protected:
  18142. void SetUp() override {
  18143. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18144. if (req.path == "/pre-routing") {
  18145. res.status = StatusCode::Unauthorized_401;
  18146. return Server::HandlerResponse::Handled;
  18147. }
  18148. return Server::HandlerResponse::Unhandled;
  18149. });
  18150. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18151. if (req.matched_route == "/pre-request") {
  18152. res.status = StatusCode::Forbidden_403;
  18153. return Server::HandlerResponse::Handled;
  18154. }
  18155. return Server::HandlerResponse::Unhandled;
  18156. });
  18157. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18158. res.set_content("ok", "text/plain");
  18159. });
  18160. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18161. res.set_content("ok", "text/plain");
  18162. });
  18163. svr_.Post("/reader-used", [](const Request &, Response &res,
  18164. const ContentReader &content_reader) {
  18165. std::string body;
  18166. content_reader([&](const char *data, size_t len) {
  18167. body.append(data, len);
  18168. return true;
  18169. });
  18170. res.set_content(body, "text/plain");
  18171. });
  18172. svr_.Post("/reader-unused",
  18173. [](const Request &, Response &res, const ContentReader &) {
  18174. res.set_content("ignored", "text/plain");
  18175. });
  18176. port_ = svr_.bind_to_any_port(HOST);
  18177. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18178. svr_.wait_until_ready();
  18179. }
  18180. void TearDown() override {
  18181. svr_.stop();
  18182. if (thread_.joinable()) { thread_.join(); }
  18183. }
  18184. // Sends `req` and reads until the server closes the connection. Returns
  18185. // false if the read had to wait for the client-side timeout instead.
  18186. bool send_until_closed(const std::string &req, std::string *resp) const {
  18187. auto start = std::chrono::steady_clock::now();
  18188. if (!send_request(3, req, resp, port_)) { return false; }
  18189. auto elapsed = std::chrono::steady_clock::now() - start;
  18190. return elapsed < std::chrono::seconds(2);
  18191. }
  18192. // The final response comes without `100 Continue`, and the server closes
  18193. // the connection since the body may or may not follow.
  18194. void expect_final_without_interim(const std::string &path,
  18195. const char *status_line) const {
  18196. std::string resp;
  18197. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18198. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18199. EXPECT_EQ(0u, resp.find(status_line));
  18200. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18201. }
  18202. Server svr_;
  18203. int port_ = 0;
  18204. thread thread_;
  18205. };
  18206. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18207. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18208. }
  18209. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18210. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18211. }
  18212. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18213. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18214. }
  18215. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18216. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18217. }
  18218. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18219. // The body follows once `100 Continue` has had time to arrive.
  18220. auto req = expect_headers_only("/reader-used");
  18221. req.insert(req.size() - 2, "Connection: close\r\n");
  18222. std::string resp;
  18223. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18224. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18225. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18226. EXPECT_NE(std::string::npos, resp.find("hi"));
  18227. }
  18228. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18229. // Large enough for the client to add `Expect: 100-continue` itself.
  18230. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18231. std::atomic<bool> body_sent{false};
  18232. Client cli(HOST, port_);
  18233. auto res = cli.Post(
  18234. "/pre-request", length,
  18235. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18236. body_sent = true;
  18237. std::string chunk(len, 'x');
  18238. sink.write(chunk.data(), chunk.size());
  18239. return true;
  18240. },
  18241. "application/octet-stream");
  18242. ASSERT_TRUE(res);
  18243. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18244. EXPECT_FALSE(body_sent);
  18245. }
  18246. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18247. Server svr;
  18248. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18249. return StatusCode::ExpectationFailed_417;
  18250. });
  18251. svr.Post("/p", [](const Request &, Response &res) {
  18252. res.set_content("ok", "text/plain");
  18253. });
  18254. auto port = svr.bind_to_any_port(HOST);
  18255. thread t = thread([&] { svr.listen_after_bind(); });
  18256. auto se = detail::scope_exit([&] {
  18257. svr.stop();
  18258. t.join();
  18259. });
  18260. svr.wait_until_ready();
  18261. std::string resp;
  18262. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18263. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18264. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18265. // Exactly one response: the route handler must not run after the 417.
  18266. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18267. }
  18268. #ifndef _WIN32
  18269. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18270. static constexpr char reject[] = "Unauthorized";
  18271. static constexpr char accept[] = "Upload accepted";
  18272. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18273. Server svr;
  18274. svr.set_expect_100_continue_handler(
  18275. [](const Request & /*req*/, Response &res) {
  18276. res.status = StatusCode::Unauthorized_401;
  18277. res.set_content(reject, "text/plain");
  18278. return res.status;
  18279. });
  18280. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18281. res.set_content(accept, "text/plain");
  18282. });
  18283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18284. auto se = detail::scope_exit([&] {
  18285. svr.stop();
  18286. thread.join();
  18287. ASSERT_FALSE(svr.is_running());
  18288. });
  18289. svr.wait_until_ready();
  18290. {
  18291. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18292. curl_easy_init(), &curl_easy_cleanup};
  18293. ASSERT_NE(curl, nullptr);
  18294. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18295. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18296. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18297. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18298. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18299. &curl_slist_free_all};
  18300. ASSERT_NE(list, nullptr);
  18301. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18302. struct read_data {
  18303. uint64_t read_size;
  18304. uint64_t total_size;
  18305. } data = {0, total_size};
  18306. using read_callback_t =
  18307. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18308. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18309. void *userdata) -> size_t {
  18310. read_data *d = (read_data *)userdata;
  18311. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18312. std::fill_n(ptr, size * nmemb, 'A');
  18313. d->read_size += size * nmemb;
  18314. return size * nmemb;
  18315. };
  18316. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18317. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18318. std::vector<char> buffer;
  18319. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18320. using write_callback_t =
  18321. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18322. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18323. void *userdata) -> size_t {
  18324. std::vector<char> *buf = (std::vector<char> *)userdata;
  18325. buf->reserve(buf->size() + size * nmemb + 1);
  18326. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18327. return size * nmemb;
  18328. };
  18329. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18330. {
  18331. const auto res = curl_easy_perform(curl.get());
  18332. ASSERT_EQ(res, CURLE_OK);
  18333. }
  18334. {
  18335. auto response_code = long{};
  18336. const auto res =
  18337. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18338. ASSERT_EQ(res, CURLE_OK);
  18339. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18340. }
  18341. {
  18342. auto dl = curl_off_t{};
  18343. const auto res =
  18344. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18345. ASSERT_EQ(res, CURLE_OK);
  18346. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18347. }
  18348. {
  18349. buffer.push_back('\0');
  18350. ASSERT_STRCASEEQ(buffer.data(), reject);
  18351. }
  18352. }
  18353. }
  18354. #endif
  18355. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18356. // Regression test for #2458.
  18357. //
  18358. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18359. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18360. // ticket can make the client socket spuriously readable during the
  18361. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18362. // the client withholds the body and then blocks reading a response that never
  18363. // comes, failing with `Failed to read connection`.
  18364. //
  18365. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18366. // within the timeout. This raw OpenSSL server deliberately never sends
  18367. // `100 Continue`; the client must still deliver the body and receive 200.
  18368. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18369. signal(SIGPIPE, SIG_IGN);
  18370. const auto port = PORT + 4;
  18371. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18372. ASSERT_NE(srv, INVALID_SOCKET);
  18373. int opt = 1;
  18374. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18375. sockaddr_in addr{};
  18376. addr.sin_family = AF_INET;
  18377. addr.sin_port = htons(static_cast<uint16_t>(port));
  18378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18379. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18380. ASSERT_EQ(0, ::listen(srv, 1));
  18381. std::atomic<size_t> server_body_bytes{0};
  18382. auto server_thread = std::thread([&] {
  18383. sockaddr_in cli_addr{};
  18384. socklen_t cli_len = sizeof(cli_addr);
  18385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18386. if (cli == INVALID_SOCKET) { return; }
  18387. // Bound the lifetime of the server side so a buggy client (which never
  18388. // sends the body) cannot make this thread block forever on join.
  18389. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18390. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18391. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18392. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18393. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18394. SSL *ssl = SSL_new(ctx);
  18395. SSL_set_fd(ssl, static_cast<int>(cli));
  18396. if (SSL_accept(ssl) > 0) {
  18397. // Read the request headers. Reading here also flushes the TLS 1.3
  18398. // session tickets to the client. Deliberately do NOT send
  18399. // `100 Continue`.
  18400. std::string buf;
  18401. char tmp[1024];
  18402. while (buf.find("\r\n\r\n") == std::string::npos) {
  18403. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18404. if (n <= 0) { break; }
  18405. buf.append(tmp, static_cast<size_t>(n));
  18406. }
  18407. // A correct client sends the body now; count what arrives.
  18408. auto pos = buf.find("\r\n\r\n");
  18409. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18410. while (body < 4096) {
  18411. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18412. if (n <= 0) { break; }
  18413. body += static_cast<size_t>(n);
  18414. }
  18415. server_body_bytes = body;
  18416. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18417. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18418. SSL_shutdown(ssl);
  18419. }
  18420. SSL_free(ssl);
  18421. detail::close_socket(cli);
  18422. SSL_CTX_free(ctx);
  18423. });
  18424. auto se = detail::scope_exit([&] {
  18425. server_thread.join();
  18426. detail::close_socket(srv);
  18427. });
  18428. SSLClient cli("127.0.0.1", port);
  18429. cli.enable_server_certificate_verification(false);
  18430. cli.set_connection_timeout(5, 0);
  18431. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18432. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18433. std::string body(4096, 'A');
  18434. auto res = cli.Put("/api/test", body, "application/json");
  18435. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18436. EXPECT_EQ(StatusCode::OK_200, res->status);
  18437. EXPECT_EQ(body.size(), server_body_bytes.load());
  18438. }
  18439. #endif
  18440. template <typename S, typename C>
  18441. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18442. svr.Get("/stream", [&](const Request &, Response &res) {
  18443. auto data = new std::string("01234567890123456789");
  18444. res.set_content_provider(
  18445. data->size(), "text/plain",
  18446. [&, data](size_t offset, size_t length, DataSink &sink) {
  18447. const size_t DATA_CHUNK_SIZE = 4;
  18448. const auto &d = *data;
  18449. std::this_thread::sleep_for(std::chrono::seconds(1));
  18450. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18451. return true;
  18452. },
  18453. [data](bool success) {
  18454. EXPECT_FALSE(success);
  18455. delete data;
  18456. });
  18457. });
  18458. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18459. auto i = new size_t(0);
  18460. res.set_content_provider(
  18461. "text/plain",
  18462. [i](size_t, DataSink &sink) {
  18463. if (*i < 5) {
  18464. std::this_thread::sleep_for(std::chrono::seconds(1));
  18465. sink.write("abcd", 4);
  18466. (*i)++;
  18467. } else {
  18468. sink.done();
  18469. }
  18470. return true;
  18471. },
  18472. [i](bool success) {
  18473. EXPECT_FALSE(success);
  18474. delete i;
  18475. });
  18476. });
  18477. svr.Get("/chunked", [&](const Request &, Response &res) {
  18478. auto i = new size_t(0);
  18479. res.set_chunked_content_provider(
  18480. "text/plain",
  18481. [i](size_t, DataSink &sink) {
  18482. if (*i < 5) {
  18483. std::this_thread::sleep_for(std::chrono::seconds(1));
  18484. sink.os << "abcd";
  18485. (*i)++;
  18486. } else {
  18487. sink.done();
  18488. }
  18489. return true;
  18490. },
  18491. [i](bool success) {
  18492. EXPECT_FALSE(success);
  18493. delete i;
  18494. });
  18495. });
  18496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18497. auto se = detail::scope_exit([&] {
  18498. svr.stop();
  18499. listen_thread.join();
  18500. ASSERT_FALSE(svr.is_running());
  18501. });
  18502. svr.wait_until_ready();
  18503. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18504. {
  18505. auto start = std::chrono::steady_clock::now();
  18506. auto res = cli.Get("/stream");
  18507. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18508. std::chrono::steady_clock::now() - start)
  18509. .count();
  18510. ASSERT_FALSE(res);
  18511. EXPECT_EQ(Error::Read, res.error());
  18512. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18513. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18514. }
  18515. {
  18516. auto start = std::chrono::steady_clock::now();
  18517. auto res = cli.Get("/stream_without_length");
  18518. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18519. std::chrono::steady_clock::now() - start)
  18520. .count();
  18521. ASSERT_FALSE(res);
  18522. EXPECT_EQ(Error::Read, res.error());
  18523. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18524. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18525. }
  18526. {
  18527. auto start = std::chrono::steady_clock::now();
  18528. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18529. EXPECT_EQ("abcd", string(data, data_length));
  18530. return true;
  18531. });
  18532. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18533. std::chrono::steady_clock::now() - start)
  18534. .count();
  18535. ASSERT_FALSE(res);
  18536. EXPECT_EQ(Error::Read, res.error());
  18537. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18538. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18539. }
  18540. }
  18541. TEST(MaxTimeoutTest, ContentStream) {
  18542. time_t timeout = 2000;
  18543. time_t threshold = 200;
  18544. Server svr;
  18545. Client cli("localhost", PORT);
  18546. max_timeout_test(svr, cli, timeout, threshold);
  18547. }
  18548. #ifdef CPPHTTPLIB_SSL_ENABLED
  18549. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18550. time_t timeout = 2000;
  18551. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18553. SSLClient cli("localhost", PORT);
  18554. cli.enable_server_certificate_verification(false);
  18555. max_timeout_test(svr, cli, timeout, threshold);
  18556. }
  18557. #endif
  18558. class EventDispatcher {
  18559. public:
  18560. EventDispatcher() {}
  18561. bool wait_event(DataSink *sink) {
  18562. unique_lock<mutex> lk(m_);
  18563. int id = id_;
  18564. // Wait with timeout to prevent hanging if client disconnects
  18565. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18566. [&] { return cid_ == id; })) {
  18567. return false; // Timeout occurred
  18568. }
  18569. sink->write(message_.data(), message_.size());
  18570. return true;
  18571. }
  18572. void send_event(const string &message) {
  18573. lock_guard<mutex> lk(m_);
  18574. cid_ = id_++;
  18575. message_ = message;
  18576. cv_.notify_all();
  18577. }
  18578. private:
  18579. mutex m_;
  18580. condition_variable cv_;
  18581. atomic_int id_{0};
  18582. atomic_int cid_{-1};
  18583. string message_;
  18584. };
  18585. TEST(ClientInThreadTest, Issue2068) {
  18586. EventDispatcher ed;
  18587. Server svr;
  18588. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18589. res.set_chunked_content_provider("text/event-stream",
  18590. [&](size_t /*offset*/, DataSink &sink) {
  18591. return ed.wait_event(&sink);
  18592. });
  18593. });
  18594. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18595. svr.wait_until_ready();
  18596. thread event_thread([&] {
  18597. int id = 0;
  18598. while (svr.is_running()) {
  18599. this_thread::sleep_for(chrono::milliseconds(500));
  18600. std::stringstream ss;
  18601. ss << "data: " << id << "\n\n";
  18602. ed.send_event(ss.str());
  18603. id++;
  18604. }
  18605. });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. listen_thread.join();
  18609. event_thread.join();
  18610. ASSERT_FALSE(svr.is_running());
  18611. });
  18612. {
  18613. auto client = detail::make_unique<Client>(HOST, PORT);
  18614. client->set_read_timeout(std::chrono::minutes(10));
  18615. std::atomic<bool> stop{false};
  18616. std::thread t([&] {
  18617. client->Get("/event1",
  18618. [&](const char *, size_t) -> bool { return !stop; });
  18619. });
  18620. std::this_thread::sleep_for(std::chrono::seconds(2));
  18621. stop = true;
  18622. client->stop();
  18623. t.join();
  18624. // Reset client after thread has finished
  18625. client.reset();
  18626. }
  18627. }
  18628. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18629. auto handled = false;
  18630. Server svr;
  18631. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18633. auto se = detail::scope_exit([&] {
  18634. svr.stop();
  18635. t.join();
  18636. ASSERT_FALSE(svr.is_running());
  18637. ASSERT_FALSE(handled);
  18638. });
  18639. svr.wait_until_ready();
  18640. // Two Content-Length headers with different values — must be rejected
  18641. auto req = "POST /test HTTP/1.1\r\n"
  18642. "Content-Length: 5\r\n"
  18643. "Content-Length: 10\r\n"
  18644. "\r\n"
  18645. "hello";
  18646. std::string response;
  18647. ASSERT_TRUE(send_request(1, req, &response));
  18648. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18649. response.substr(0, response.find("\r\n")));
  18650. }
  18651. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18652. auto handled = false;
  18653. Server svr;
  18654. svr.Post("/test", [&](const Request &, Response &res) {
  18655. handled = true;
  18656. res.set_content("ok", "text/plain");
  18657. });
  18658. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18659. auto se = detail::scope_exit([&] {
  18660. svr.stop();
  18661. t.join();
  18662. ASSERT_FALSE(svr.is_running());
  18663. ASSERT_TRUE(handled);
  18664. });
  18665. svr.wait_until_ready();
  18666. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18667. auto req = "POST /test HTTP/1.1\r\n"
  18668. "Host: localhost\r\n"
  18669. "Content-Length: 5\r\n"
  18670. "Content-Length: 5\r\n"
  18671. "\r\n"
  18672. "hello";
  18673. std::string response;
  18674. ASSERT_TRUE(send_request(1, req, &response));
  18675. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18676. }
  18677. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18678. Server svr;
  18679. svr.Get("/test", [](const Request &, Response &res) {
  18680. res.set_content("ok", "text/plain");
  18681. });
  18682. auto port = svr.bind_to_any_port(HOST);
  18683. thread t = thread([&] { svr.listen_after_bind(); });
  18684. auto se = detail::scope_exit([&] {
  18685. svr.stop();
  18686. t.join();
  18687. ASSERT_FALSE(svr.is_running());
  18688. });
  18689. svr.wait_until_ready();
  18690. auto status_line = [&](const std::string &host_lines) {
  18691. std::string res;
  18692. send_request(
  18693. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18694. &res, port);
  18695. return res.substr(0, res.find("\r\n"));
  18696. };
  18697. const char *accepted[] = {
  18698. "Host: localhost\r\n",
  18699. "Host: a.example:8080\r\n",
  18700. "Host: my_service\r\n",
  18701. "Host: [::1]:8080\r\n",
  18702. "Host: [fe80::1%25eth0]\r\n",
  18703. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18704. };
  18705. for (auto host_lines : accepted) {
  18706. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18707. }
  18708. const char *rejected[] = {
  18709. "Host: a.example\r\nHost: b.example\r\n",
  18710. "Host: a.example\r\nHost: a.example\r\n",
  18711. "Host: a@b.example\r\n",
  18712. "Host: a.example/b\r\n",
  18713. "Host: a.example\\b\r\n",
  18714. "Host: a.example?b\r\n",
  18715. "Host: a.example#b\r\n",
  18716. "Host: a.example b.example\r\n",
  18717. };
  18718. for (auto host_lines : rejected) {
  18719. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18720. << host_lines;
  18721. }
  18722. }
  18723. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18724. Server svr;
  18725. svr.Get("/", [](const Request &req, Response &res) {
  18726. EXPECT_EQ(2U, req.trailers.size());
  18727. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18728. // Denied
  18729. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18730. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18731. // Accepted
  18732. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18733. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18734. EXPECT_TRUE(req.has_trailer("X-World"));
  18735. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18736. res.set_content("ok", "text/plain");
  18737. });
  18738. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18739. auto se = detail::scope_exit([&] {
  18740. svr.stop();
  18741. t.join();
  18742. ASSERT_FALSE(svr.is_running());
  18743. });
  18744. svr.wait_until_ready();
  18745. const std::string req = "GET / HTTP/1.1\r\n"
  18746. "Transfer-Encoding: chunked\r\n"
  18747. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18748. "\r\n"
  18749. "0\r\n"
  18750. "Content-Length: 10\r\n"
  18751. "Host: internal.local\r\n"
  18752. "Content-Type: malicious/content\r\n"
  18753. "Cookie: any\r\n"
  18754. "Set-Cookie: any\r\n"
  18755. "X-Forwarded-For: attacker.com\r\n"
  18756. "X-Real-Ip: 1.1.1.1\r\n"
  18757. "X-Hello: hello\r\n"
  18758. "X-World: world\r\n"
  18759. "\r\n";
  18760. std::string res;
  18761. ASSERT_TRUE(send_request(1, req, &res));
  18762. }
  18763. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18764. // several field lines, and the combined value is what has to be parsed. A
  18765. // Trailer field split across lines therefore declares every name it lists;
  18766. // reading only the first line silently drops the trailers the later lines
  18767. // declare. The prohibited-trailer filter still applies to every line.
  18768. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18769. Server svr;
  18770. size_t observed_trailer_count = 0;
  18771. std::string observed_hello;
  18772. std::string observed_world;
  18773. bool observed_content_length = true;
  18774. svr.Get("/", [&](const Request &req, Response &res) {
  18775. observed_trailer_count = req.trailers.size();
  18776. observed_hello = req.get_trailer_value("X-Hello");
  18777. observed_world = req.get_trailer_value("X-World");
  18778. observed_content_length = req.has_trailer("Content-Length");
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&]() { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. const std::string req = "GET / HTTP/1.1\r\n"
  18790. "Host: localhost\r\n"
  18791. "Transfer-Encoding: chunked\r\n"
  18792. "Trailer: X-Hello\r\n"
  18793. "Trailer: X-World, Content-Length\r\n"
  18794. "\r\n"
  18795. "0\r\n"
  18796. "X-Hello: hello\r\n"
  18797. "X-World: world\r\n"
  18798. "Content-Length: 10\r\n"
  18799. "\r\n";
  18800. std::string res;
  18801. ASSERT_TRUE(send_request(1, req, &res, port));
  18802. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18803. // Accepted: both field lines contribute to the declared set
  18804. EXPECT_EQ(2U, observed_trailer_count);
  18805. EXPECT_EQ(observed_hello, "hello");
  18806. EXPECT_EQ(observed_world, "world");
  18807. // Denied: a prohibited name stays prohibited on a later field line
  18808. EXPECT_FALSE(observed_content_length);
  18809. }
  18810. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18811. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18812. // unbounded run of fields that are never declared, because the counter would
  18813. // only advance for declared fields.
  18814. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18815. Server svr;
  18816. bool handler_called = false;
  18817. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18818. handler_called = true;
  18819. res.set_content("ok", "text/plain");
  18820. });
  18821. auto port = svr.bind_to_any_port(HOST);
  18822. thread t = thread([&]() { svr.listen_after_bind(); });
  18823. auto se = detail::scope_exit([&] {
  18824. svr.stop();
  18825. t.join();
  18826. ASSERT_FALSE(svr.is_running());
  18827. });
  18828. svr.wait_until_ready();
  18829. // Declare nothing, then send far more undeclared trailer fields than the
  18830. // header-count limit. Parsing must stop and reject the request rather than
  18831. // read every line.
  18832. std::string req = "GET / HTTP/1.1\r\n"
  18833. "Transfer-Encoding: chunked\r\n"
  18834. "\r\n"
  18835. "0\r\n";
  18836. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18837. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18838. }
  18839. req += "\r\n";
  18840. std::string res;
  18841. ASSERT_TRUE(send_request(1, req, &res, port));
  18842. // The request is rejected before the handler runs.
  18843. EXPECT_FALSE(handler_called);
  18844. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18845. }
  18846. // The set of declared trailer names is capped so a peer cannot grow it without
  18847. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18848. // declared past the cap is not honored, even if the field is actually sent.
  18849. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18850. Server svr;
  18851. // One name inside the cap and one past it, so the test tracks the cap rather
  18852. // than a fixed count.
  18853. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18854. const std::string within_cap_name = "X-T-0";
  18855. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18856. bool observed_within_cap = false;
  18857. bool observed_past_cap = false;
  18858. svr.Get("/", [&](const Request &req, Response &res) {
  18859. observed_within_cap = req.has_trailer(within_cap_name);
  18860. observed_past_cap = req.has_trailer(past_cap_name);
  18861. res.set_content("ok", "text/plain");
  18862. });
  18863. auto port = svr.bind_to_any_port(HOST);
  18864. thread t = thread([&]() { svr.listen_after_bind(); });
  18865. auto se = detail::scope_exit([&] {
  18866. svr.stop();
  18867. t.join();
  18868. ASSERT_FALSE(svr.is_running());
  18869. });
  18870. svr.wait_until_ready();
  18871. // Declare more trailer names than the cap in a single Trailer field, then
  18872. // actually send the first (within the cap) and the last (past it).
  18873. std::string trailer_decl = "Trailer: ";
  18874. for (int i = 0; i < declared_count; i++) {
  18875. if (i != 0) { trailer_decl += ", "; }
  18876. trailer_decl += "X-T-" + std::to_string(i);
  18877. }
  18878. trailer_decl += "\r\n";
  18879. const std::string req = "GET / HTTP/1.1\r\n"
  18880. "Host: localhost\r\n"
  18881. "Transfer-Encoding: chunked\r\n" +
  18882. trailer_decl +
  18883. "\r\n"
  18884. "0\r\n" +
  18885. within_cap_name + ": a\r\n" + past_cap_name +
  18886. ": b\r\n"
  18887. "\r\n";
  18888. std::string res;
  18889. ASSERT_TRUE(send_request(1, req, &res, port));
  18890. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18891. // A name within the cap is honored; one declared past the cap is dropped.
  18892. EXPECT_TRUE(observed_within_cap);
  18893. EXPECT_FALSE(observed_past_cap);
  18894. }
  18895. // A direct client that is not listed in trusted_proxies must not be able to
  18896. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18897. // the peer address on the actual TCP connection determines whether the
  18898. // header is honored.
  18899. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18900. Server svr;
  18901. // Deliberately does NOT include the loopback address the test client
  18902. // actually connects from, so the direct connection is not a trusted proxy.
  18903. svr.set_trusted_proxies({"203.0.113.66"});
  18904. std::string observed_remote_addr;
  18905. svr.Get("/ip", [&](const Request &req, Response &res) {
  18906. observed_remote_addr = req.remote_addr;
  18907. res.set_content("ok", "text/plain");
  18908. });
  18909. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18910. auto se = detail::scope_exit([&] {
  18911. svr.stop();
  18912. t.join();
  18913. ASSERT_FALSE(svr.is_running());
  18914. });
  18915. svr.wait_until_ready();
  18916. Client cli(HOST, PORT);
  18917. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18919. EXPECT_EQ(StatusCode::OK_200, res->status);
  18920. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18921. // ignored entirely and the real connection-level address retained.
  18922. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18923. observed_remote_addr == "127.0.0.1");
  18924. }
  18925. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18926. Server svr;
  18927. std::string observed_remote_addr;
  18928. std::string observed_xff;
  18929. svr.Get("/ip", [&](const Request &req, Response &res) {
  18930. observed_remote_addr = req.remote_addr;
  18931. observed_xff = req.get_header_value("X-Forwarded-For");
  18932. res.set_content("ok", "text/plain");
  18933. });
  18934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18935. auto se = detail::scope_exit([&] {
  18936. svr.stop();
  18937. t.join();
  18938. ASSERT_FALSE(svr.is_running());
  18939. });
  18940. svr.wait_until_ready();
  18941. Client cli(HOST, PORT);
  18942. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18944. EXPECT_EQ(StatusCode::OK_200, res->status);
  18945. EXPECT_EQ(observed_xff, "203.0.113.66");
  18946. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18947. observed_remote_addr == "127.0.0.1");
  18948. }
  18949. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18950. Server svr;
  18951. svr.set_trusted_proxies({"203.0.113.66"});
  18952. std::string observed_remote_addr;
  18953. std::string observed_xff;
  18954. svr.Get("/ip", [&](const Request &req, Response &res) {
  18955. observed_remote_addr = req.remote_addr;
  18956. observed_xff = req.get_header_value("X-Forwarded-For");
  18957. res.set_content("ok", "text/plain");
  18958. });
  18959. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18960. auto se = detail::scope_exit([&] {
  18961. svr.stop();
  18962. t.join();
  18963. ASSERT_FALSE(svr.is_running());
  18964. });
  18965. svr.wait_until_ready();
  18966. Client cli(HOST, PORT);
  18967. auto res = cli.Get("/ip");
  18968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18969. EXPECT_EQ(StatusCode::OK_200, res->status);
  18970. EXPECT_EQ(observed_xff, "");
  18971. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18972. observed_remote_addr == "127.0.0.1");
  18973. }
  18974. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18975. Server svr;
  18976. // Include the loopback address the test client actually connects from, so
  18977. // the direct connection itself is recognized as the trusted proxy hop.
  18978. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18979. std::string observed_remote_addr;
  18980. std::string observed_xff;
  18981. svr.Get("/ip", [&](const Request &req, Response &res) {
  18982. observed_remote_addr = req.remote_addr;
  18983. observed_xff = req.get_header_value("X-Forwarded-For");
  18984. res.set_content("ok", "text/plain");
  18985. });
  18986. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18987. auto se = detail::scope_exit([&] {
  18988. svr.stop();
  18989. t.join();
  18990. ASSERT_FALSE(svr.is_running());
  18991. });
  18992. svr.wait_until_ready();
  18993. Client cli(HOST, PORT);
  18994. auto res = cli.Get(
  18995. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18997. EXPECT_EQ(StatusCode::OK_200, res->status);
  18998. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18999. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19000. }
  19001. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19002. Server svr;
  19003. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19004. std::string observed_remote_addr;
  19005. std::string observed_xff;
  19006. svr.Get("/ip", [&](const Request &req, Response &res) {
  19007. observed_remote_addr = req.remote_addr;
  19008. observed_xff = req.get_header_value("X-Forwarded-For");
  19009. res.set_content("ok", "text/plain");
  19010. });
  19011. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19012. auto se = detail::scope_exit([&] {
  19013. svr.stop();
  19014. t.join();
  19015. ASSERT_FALSE(svr.is_running());
  19016. });
  19017. svr.wait_until_ready();
  19018. Client cli(HOST, PORT);
  19019. auto res = cli.Get(
  19020. "/ip",
  19021. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19023. EXPECT_EQ(StatusCode::OK_200, res->status);
  19024. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19025. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19026. }
  19027. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19028. Server svr;
  19029. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19030. std::string observed_remote_addr;
  19031. std::string observed_xff;
  19032. svr.Get("/ip", [&](const Request &req, Response &res) {
  19033. observed_remote_addr = req.remote_addr;
  19034. observed_xff = req.get_header_value("X-Forwarded-For");
  19035. res.set_content("ok", "text/plain");
  19036. });
  19037. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19038. auto se = detail::scope_exit([&] {
  19039. svr.stop();
  19040. t.join();
  19041. ASSERT_FALSE(svr.is_running());
  19042. });
  19043. svr.wait_until_ready();
  19044. Client cli(HOST, PORT);
  19045. auto res = cli.Get(
  19046. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19048. EXPECT_EQ(StatusCode::OK_200, res->status);
  19049. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19050. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19051. // and must not be selected.
  19052. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19053. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19054. }
  19055. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19056. Server svr;
  19057. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19058. std::string observed_remote_addr;
  19059. svr.Get("/ip", [&](const Request &req, Response &res) {
  19060. observed_remote_addr = req.remote_addr;
  19061. res.set_content("ok", "text/plain");
  19062. });
  19063. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19064. auto se = detail::scope_exit([&] {
  19065. svr.stop();
  19066. t.join();
  19067. ASSERT_FALSE(svr.is_running());
  19068. });
  19069. svr.wait_until_ready();
  19070. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19071. // a forged address and the trusted proxy's own address; the forged value must
  19072. // not win over the address the trusted proxy actually recorded.
  19073. Client cli(HOST, PORT);
  19074. auto res = cli.Get(
  19075. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19077. EXPECT_EQ(StatusCode::OK_200, res->status);
  19078. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19079. }
  19080. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19081. Server svr;
  19082. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19083. std::string observed_remote_addr;
  19084. std::string observed_xff;
  19085. svr.Get("/ip", [&](const Request &req, Response &res) {
  19086. observed_remote_addr = req.remote_addr;
  19087. observed_xff = req.get_header_value("X-Forwarded-For");
  19088. res.set_content("ok", "text/plain");
  19089. });
  19090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19091. auto se = detail::scope_exit([&] {
  19092. svr.stop();
  19093. t.join();
  19094. ASSERT_FALSE(svr.is_running());
  19095. });
  19096. svr.wait_until_ready();
  19097. Client cli(HOST, PORT);
  19098. auto res = cli.Get(
  19099. "/ip",
  19100. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19102. EXPECT_EQ(StatusCode::OK_200, res->status);
  19103. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19104. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19105. }
  19106. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19107. Server svr;
  19108. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19109. std::string observed_remote_addr;
  19110. std::string observed_xff;
  19111. svr.Get("/ip", [&](const Request &req, Response &res) {
  19112. observed_remote_addr = req.remote_addr;
  19113. observed_xff = req.get_header_value("X-Forwarded-For");
  19114. res.set_content("ok", "text/plain");
  19115. });
  19116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19117. auto se = detail::scope_exit([&] {
  19118. svr.stop();
  19119. t.join();
  19120. ASSERT_FALSE(svr.is_running());
  19121. });
  19122. svr.wait_until_ready();
  19123. std::string raw_req =
  19124. "GET /ip HTTP/1.1\r\n"
  19125. "Host: localhost\r\n"
  19126. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19127. "Connection: close\r\n"
  19128. "\r\n";
  19129. std::string out;
  19130. ASSERT_TRUE(send_request(5, raw_req, &out));
  19131. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19132. // Header parser trims surrounding whitespace of the header value
  19133. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19134. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19135. }
  19136. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19137. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19138. // their own X-Forwarded-For as a separate field line rather than extending the
  19139. // one the client sent, so every occurrence has to be taken into account.
  19140. // Reading only the first one hands back the address the client chose.
  19141. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19142. Server svr;
  19143. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19144. std::string observed_remote_addr;
  19145. size_t observed_xff_count = 0;
  19146. svr.Get("/ip", [&](const Request &req, Response &res) {
  19147. observed_remote_addr = req.remote_addr;
  19148. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19149. res.set_content("ok", "text/plain");
  19150. });
  19151. auto port = svr.bind_to_any_port(HOST);
  19152. thread t = thread([&]() { svr.listen_after_bind(); });
  19153. auto se = detail::scope_exit([&] {
  19154. svr.stop();
  19155. t.join();
  19156. ASSERT_FALSE(svr.is_running());
  19157. });
  19158. svr.wait_until_ready();
  19159. // The client supplies the first field line; the trusted proxy appends the
  19160. // address it observed as a second one.
  19161. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19162. "Host: localhost\r\n"
  19163. "X-Forwarded-For: 1.2.3.4\r\n"
  19164. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19165. "Connection: close\r\n"
  19166. "\r\n";
  19167. std::string out;
  19168. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19169. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19170. EXPECT_EQ(observed_xff_count, 2U);
  19171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19172. // The same chain spread over one field line per hop derives the same client
  19173. // address, i.e. the split and the comma-joined representations agree.
  19174. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19175. "Host: localhost\r\n"
  19176. "X-Forwarded-For: 1.2.3.4\r\n"
  19177. "X-Forwarded-For: 198.51.100.23\r\n"
  19178. "X-Forwarded-For: 192.0.2.45\r\n"
  19179. "Connection: close\r\n"
  19180. "\r\n";
  19181. out.clear();
  19182. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19183. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19184. EXPECT_EQ(observed_xff_count, 3U);
  19185. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19186. }
  19187. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19188. // crash the server (it used to call front() on an empty vector inside
  19189. // get_client_ip). The connection-level remote address must be retained instead.
  19190. static void run_malformed_xff_test(const std::string &xff_value) {
  19191. Server svr;
  19192. svr.set_trusted_proxies({"192.0.2.45"});
  19193. std::string observed_remote_addr;
  19194. svr.Get("/ip", [&](const Request &req, Response &res) {
  19195. observed_remote_addr = req.remote_addr;
  19196. res.set_content("ok", "text/plain");
  19197. });
  19198. int port = 0;
  19199. thread t = thread([&]() {
  19200. port = svr.bind_to_any_port(HOST);
  19201. svr.listen_after_bind();
  19202. });
  19203. auto se = detail::scope_exit([&] {
  19204. svr.stop();
  19205. t.join();
  19206. ASSERT_FALSE(svr.is_running());
  19207. });
  19208. svr.wait_until_ready();
  19209. Client cli(HOST, port);
  19210. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19212. EXPECT_EQ(StatusCode::OK_200, res->status);
  19213. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19214. observed_remote_addr == "127.0.0.1");
  19215. }
  19216. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19217. run_malformed_xff_test("");
  19218. }
  19219. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19220. run_malformed_xff_test(",");
  19221. }
  19222. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19223. run_malformed_xff_test(", , ,");
  19224. }
  19225. // The same rule applies to Accept: a request whose acceptable types are spread
  19226. // over several field lines must be negotiated against all of them.
  19227. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19228. // case-insensitive connection options. Comparing the whole field value against
  19229. // one option misses a client that sends several of them, and misses every
  19230. // casing but the one written in the comparison.
  19231. //
  19232. // Sends req, reads the response, then reuses the same socket for a second
  19233. // request to find out whether the server kept the connection.
  19234. static void probe_connection_reuse(int port, const std::string &req,
  19235. bool *announced_close, bool *reusable) {
  19236. auto error = Error::Success;
  19237. auto sock = detail::create_client_socket(
  19238. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19239. /*connection_timeout_sec=*/5, 0,
  19240. /*read_timeout_sec=*/1, 0,
  19241. /*write_timeout_sec=*/5, 0, std::string(), error);
  19242. ASSERT_NE(sock, INVALID_SOCKET);
  19243. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19244. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19245. "Host: localhost\r\n"
  19246. "Connection: close\r\n"
  19247. "\r\n";
  19248. std::string first_response;
  19249. std::string second_response;
  19250. detail::process_client_socket(
  19251. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19252. [&](Stream &strm) {
  19253. if (strm.write(req.data(), req.size()) !=
  19254. static_cast<ssize_t>(req.size())) {
  19255. return false;
  19256. }
  19257. char buf[512];
  19258. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19259. // Headers plus the two-byte body of the handler below
  19260. while (reader.getline()) {
  19261. first_response += reader.ptr();
  19262. if (first_response.find("ok") != std::string::npos) { break; }
  19263. }
  19264. if (strm.write(second.data(), second.size()) !=
  19265. static_cast<ssize_t>(second.size())) {
  19266. return true;
  19267. }
  19268. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19269. while (reader2.getline()) {
  19270. second_response += reader2.ptr();
  19271. if (second_response.find("ok") != std::string::npos) { break; }
  19272. }
  19273. return true;
  19274. });
  19275. *announced_close =
  19276. first_response.find("Connection: close") != std::string::npos;
  19277. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19278. }
  19279. class ConnectionTokenTest : public ::testing::Test {
  19280. protected:
  19281. void SetUp() override {
  19282. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19283. res.set_content("ok", "text/plain");
  19284. });
  19285. port_ = svr_.bind_to_any_port(HOST);
  19286. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19287. svr_.wait_until_ready();
  19288. }
  19289. void TearDown() override {
  19290. svr_.stop();
  19291. if (thread_.joinable()) { thread_.join(); }
  19292. }
  19293. Server svr_;
  19294. int port_ = 0;
  19295. thread thread_;
  19296. };
  19297. // "close" alongside another option still closes the connection, and the
  19298. // response says so rather than leaving the peer to discover it.
  19299. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19300. bool announced_close = false;
  19301. bool reusable = true;
  19302. probe_connection_reuse(port_,
  19303. "GET /keepalive HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "Connection: keep-alive, close\r\n"
  19306. "\r\n",
  19307. &announced_close, &reusable);
  19308. EXPECT_TRUE(announced_close);
  19309. EXPECT_FALSE(reusable);
  19310. }
  19311. // "close" split over two field lines is the same list, so it is honored too.
  19312. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19313. bool announced_close = false;
  19314. bool reusable = true;
  19315. probe_connection_reuse(port_,
  19316. "GET /keepalive HTTP/1.1\r\n"
  19317. "Host: localhost\r\n"
  19318. "Connection: keep-alive\r\n"
  19319. "Connection: close\r\n"
  19320. "\r\n",
  19321. &announced_close, &reusable);
  19322. EXPECT_TRUE(announced_close);
  19323. EXPECT_FALSE(reusable);
  19324. }
  19325. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19326. // keep-alive in the spelling everyone actually sends keeps its connection.
  19327. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19328. bool announced_close = false;
  19329. bool reusable = false;
  19330. probe_connection_reuse(port_,
  19331. "GET /keepalive HTTP/1.0\r\n"
  19332. "Host: localhost\r\n"
  19333. "Connection: keep-alive\r\n"
  19334. "\r\n",
  19335. &announced_close, &reusable);
  19336. EXPECT_FALSE(announced_close);
  19337. EXPECT_TRUE(reusable);
  19338. }
  19339. // A token the value merely contains is not the token itself.
  19340. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19341. bool announced_close = false;
  19342. bool reusable = false;
  19343. probe_connection_reuse(port_,
  19344. "GET /keepalive HTTP/1.1\r\n"
  19345. "Host: localhost\r\n"
  19346. "Connection: notclose\r\n"
  19347. "\r\n",
  19348. &announced_close, &reusable);
  19349. EXPECT_FALSE(announced_close);
  19350. EXPECT_TRUE(reusable);
  19351. }
  19352. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19353. Server svr;
  19354. std::vector<std::string> observed_types;
  19355. svr.Get("/", [&](const Request &req, Response &res) {
  19356. observed_types = req.accept_content_types;
  19357. res.set_content("ok", "text/plain");
  19358. });
  19359. auto port = svr.bind_to_any_port(HOST);
  19360. thread t = thread([&]() { svr.listen_after_bind(); });
  19361. auto se = detail::scope_exit([&] {
  19362. svr.stop();
  19363. t.join();
  19364. ASSERT_FALSE(svr.is_running());
  19365. });
  19366. svr.wait_until_ready();
  19367. Client cli(HOST, port);
  19368. Headers headers;
  19369. headers.emplace("Accept", "text/plain;q=0.5");
  19370. headers.emplace("Accept", "application/json");
  19371. auto res = cli.Get("/", headers);
  19372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19373. EXPECT_EQ(StatusCode::OK_200, res->status);
  19374. // Sorted by q-value, so the second field line's type comes first
  19375. ASSERT_EQ(2U, observed_types.size());
  19376. EXPECT_EQ("application/json", observed_types[0]);
  19377. EXPECT_EQ("text/plain", observed_types[1]);
  19378. }
  19379. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19380. // empty field line must not contribute a bare comma to the combined value.
  19381. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19382. Server svr;
  19383. std::vector<std::string> observed_types;
  19384. svr.Get("/", [&](const Request &req, Response &res) {
  19385. observed_types = req.accept_content_types;
  19386. res.set_content("ok", "text/plain");
  19387. });
  19388. auto port = svr.bind_to_any_port(HOST);
  19389. thread t = thread([&]() { svr.listen_after_bind(); });
  19390. auto se = detail::scope_exit([&] {
  19391. svr.stop();
  19392. t.join();
  19393. ASSERT_FALSE(svr.is_running());
  19394. });
  19395. svr.wait_until_ready();
  19396. // Empty first field line, then a real one
  19397. std::string raw_req = "GET / HTTP/1.1\r\n"
  19398. "Host: localhost\r\n"
  19399. "Accept:\r\n"
  19400. "Accept: application/json\r\n"
  19401. "Connection: close\r\n"
  19402. "\r\n";
  19403. std::string out;
  19404. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19405. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19406. ASSERT_EQ(1U, observed_types.size());
  19407. EXPECT_EQ("application/json", observed_types[0]);
  19408. }
  19409. // The skip in get_combined_header_value() is what keeps an empty field line
  19410. // from contributing a bare comma. Only a trailing empty field line exercises
  19411. // it: a leading one is already covered by the "combined is still empty" check,
  19412. // and parse_accept_header() now ignores the empty element either way, so the
  19413. // request-level test above can no longer tell the two apart.
  19414. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19415. Headers headers;
  19416. headers.emplace("Accept", "text/html");
  19417. headers.emplace("Accept", "");
  19418. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19419. headers.clear();
  19420. headers.emplace("Accept", "");
  19421. headers.emplace("Accept", "application/json");
  19422. EXPECT_EQ("application/json",
  19423. detail::get_combined_header_value(headers, "Accept"));
  19424. }
  19425. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19426. // An encoding offered on a later Accept-Encoding field line is still offered.
  19427. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19428. Server svr;
  19429. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19430. res.set_content(std::string(1024, 'x'), "text/plain");
  19431. });
  19432. auto port = svr.bind_to_any_port(HOST);
  19433. thread t = thread([&]() { svr.listen_after_bind(); });
  19434. auto se = detail::scope_exit([&] {
  19435. svr.stop();
  19436. t.join();
  19437. ASSERT_FALSE(svr.is_running());
  19438. });
  19439. svr.wait_until_ready();
  19440. Client cli(HOST, port);
  19441. cli.set_decompress(false);
  19442. Headers headers;
  19443. headers.emplace("Accept-Encoding", "identity");
  19444. headers.emplace("Accept-Encoding", "gzip");
  19445. auto res = cli.Get("/", headers);
  19446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19447. EXPECT_EQ(StatusCode::OK_200, res->status);
  19448. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19449. }
  19450. #endif
  19451. #ifndef _WIN32
  19452. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19453. Server svr;
  19454. svr.Post("/post", [&](const Request &req, Response &res) {
  19455. res.set_content(req.body, "text/plain");
  19456. });
  19457. svr.Put("/put", [&](const Request &req, Response &res) {
  19458. res.set_content(req.body, "text/plain");
  19459. });
  19460. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19461. res.set_content(req.body, "text/plain");
  19462. });
  19463. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19464. res.set_content(req.body, "text/plain");
  19465. });
  19466. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19467. auto se = detail::scope_exit([&] {
  19468. svr.stop();
  19469. t.join();
  19470. ASSERT_FALSE(svr.is_running());
  19471. });
  19472. svr.wait_until_ready();
  19473. std::string resp;
  19474. // POST without Content-Length
  19475. ASSERT_TRUE(send_request(5,
  19476. "POST /post HTTP/1.1\r\n"
  19477. "Host: localhost\r\n"
  19478. "Connection: close\r\n"
  19479. "\r\n",
  19480. &resp));
  19481. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19482. // PUT without Content-Length
  19483. resp.clear();
  19484. ASSERT_TRUE(send_request(5,
  19485. "PUT /put HTTP/1.1\r\n"
  19486. "Host: localhost\r\n"
  19487. "Connection: close\r\n"
  19488. "\r\n",
  19489. &resp));
  19490. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19491. // PATCH without Content-Length
  19492. resp.clear();
  19493. ASSERT_TRUE(send_request(5,
  19494. "PATCH /patch HTTP/1.1\r\n"
  19495. "Host: localhost\r\n"
  19496. "Connection: close\r\n"
  19497. "\r\n",
  19498. &resp));
  19499. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19500. // DELETE without Content-Length
  19501. resp.clear();
  19502. ASSERT_TRUE(send_request(5,
  19503. "DELETE /delete HTTP/1.1\r\n"
  19504. "Host: localhost\r\n"
  19505. "Connection: close\r\n"
  19506. "\r\n",
  19507. &resp));
  19508. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19509. }
  19510. #endif
  19511. //==============================================================================
  19512. // open_stream() Tests
  19513. //==============================================================================
  19514. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19515. std::string result;
  19516. char buf[8192];
  19517. ssize_t n;
  19518. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19519. result.append(buf, static_cast<size_t>(n));
  19520. }
  19521. return result;
  19522. }
  19523. // Mock stream for unit tests
  19524. class MockStream : public Stream {
  19525. public:
  19526. std::string data;
  19527. size_t pos = 0;
  19528. ssize_t error_after = -1; // -1 = no error
  19529. explicit MockStream(const std::string &d, ssize_t err = -1)
  19530. : data(d), error_after(err) {}
  19531. bool is_readable() const override { return true; }
  19532. bool wait_readable() const override { return true; }
  19533. bool wait_writable() const override { return true; }
  19534. ssize_t read(char *ptr, size_t size) override {
  19535. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19536. if (pos >= data.size()) return 0;
  19537. size_t limit =
  19538. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19539. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19540. std::memcpy(ptr, data.data() + pos, to_read);
  19541. pos += to_read;
  19542. return static_cast<ssize_t>(to_read);
  19543. }
  19544. ssize_t write(const char *, size_t) override { return -1; }
  19545. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19546. ip = "127.0.0.1";
  19547. port = 0;
  19548. }
  19549. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19550. ip = "127.0.0.1";
  19551. port = 0;
  19552. }
  19553. socket_t socket() const override { return INVALID_SOCKET; }
  19554. time_t duration() const override { return 0; }
  19555. };
  19556. TEST(StreamHandleTest, Basic) {
  19557. ClientImpl::StreamHandle handle;
  19558. EXPECT_FALSE(handle.is_valid());
  19559. handle.response = detail::make_unique<Response>();
  19560. handle.error = Error::Connection;
  19561. EXPECT_FALSE(handle.is_valid());
  19562. handle.error = Error::Success;
  19563. EXPECT_TRUE(handle.is_valid());
  19564. }
  19565. TEST(BodyReaderTest, Basic) {
  19566. MockStream stream("Hello, World!");
  19567. detail::BodyReader reader;
  19568. reader.stream = &stream;
  19569. reader.content_length = 13;
  19570. char buf[32];
  19571. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19572. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19573. EXPECT_TRUE(reader.eof);
  19574. }
  19575. TEST(BodyReaderTest, NoStream) {
  19576. detail::BodyReader reader;
  19577. char buf[32];
  19578. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19579. EXPECT_EQ(Error::Connection, reader.last_error);
  19580. }
  19581. TEST(BodyReaderTest, Error) {
  19582. MockStream stream("Hello, World!", 5);
  19583. detail::BodyReader reader;
  19584. reader.stream = &stream;
  19585. reader.content_length = 13;
  19586. char buf[32];
  19587. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19588. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19589. EXPECT_EQ(Error::Read, reader.last_error);
  19590. }
  19591. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19592. // Mock-based StreamHandle tests relying on private internals are removed.
  19593. class OpenStreamTest : public ::testing::Test {
  19594. protected:
  19595. void SetUp() override {
  19596. svr_.Get("/hello", [](const Request &, Response &res) {
  19597. res.set_content("Hello World!", "text/plain");
  19598. });
  19599. svr_.Get("/large", [](const Request &, Response &res) {
  19600. res.set_content(std::string(10000, 'X'), "text/plain");
  19601. });
  19602. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19603. res.set_content("Hello World!", "image/jpeg");
  19604. res.set_header("Content-Encoding", "UTF-8");
  19605. });
  19606. svr_.Get("/chunked", [](const Request &, Response &res) {
  19607. res.set_chunked_content_provider("text/plain",
  19608. [](size_t offset, DataSink &sink) {
  19609. if (offset < 15) {
  19610. sink.write("chunk", 5);
  19611. return true;
  19612. }
  19613. sink.done();
  19614. return true;
  19615. });
  19616. });
  19617. svr_.Get("/compressible", [](const Request &, Response &res) {
  19618. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19619. DataSink &sink) {
  19620. if (offset < 100 * 1024) {
  19621. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19622. sink.write(chunk.data(), chunk.size());
  19623. return true;
  19624. }
  19625. sink.done();
  19626. return true;
  19627. });
  19628. });
  19629. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19630. [](const Request & /*req*/, Response &res) {
  19631. auto i = new int(0);
  19632. res.set_header("Trailer", "Content-Length, X-Allowed");
  19633. res.set_chunked_content_provider(
  19634. "text/plain",
  19635. [i](size_t /*offset*/, DataSink &sink) {
  19636. switch (*i) {
  19637. case 0: sink.os << "123"; break;
  19638. case 1: sink.os << "456"; break;
  19639. case 2: sink.os << "789"; break;
  19640. case 3: {
  19641. sink.done_with_trailer(
  19642. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19643. } break;
  19644. }
  19645. (*i)++;
  19646. return true;
  19647. },
  19648. [i](bool success) {
  19649. EXPECT_TRUE(success);
  19650. delete i;
  19651. });
  19652. });
  19653. // Echo headers endpoint for header-related tests
  19654. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19655. std::string body;
  19656. for (const auto &h : req.headers) {
  19657. body.append(h.first);
  19658. body.push_back(':');
  19659. body.append(h.second);
  19660. body.push_back('\n');
  19661. }
  19662. res.set_content(body, "text/plain");
  19663. });
  19664. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19665. std::string body;
  19666. for (const auto &h : req.headers) {
  19667. body.append(h.first);
  19668. body.push_back(':');
  19669. body.append(h.second);
  19670. body.push_back('\n');
  19671. }
  19672. res.set_content(body, "text/plain");
  19673. });
  19674. port_ = svr_.bind_to_any_port("127.0.0.1");
  19675. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19676. svr_.wait_until_ready();
  19677. }
  19678. void TearDown() override {
  19679. svr_.stop();
  19680. if (thread_.joinable()) thread_.join();
  19681. }
  19682. Server svr_;
  19683. std::thread thread_;
  19684. int port_ = 0;
  19685. };
  19686. TEST_F(OpenStreamTest, Basic) {
  19687. Client cli("127.0.0.1", port_);
  19688. auto handle = cli.open_stream("GET", "/hello");
  19689. EXPECT_TRUE(handle.is_valid());
  19690. EXPECT_EQ("Hello World!", read_all(handle));
  19691. }
  19692. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19693. Client cli("127.0.0.1", port_);
  19694. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19695. ASSERT_TRUE(handle.is_valid());
  19696. EXPECT_EQ("Hello World!", read_all(handle));
  19697. }
  19698. TEST_F(OpenStreamTest, SmallBuffer) {
  19699. Client cli("127.0.0.1", port_);
  19700. auto handle = cli.open_stream("GET", "/hello");
  19701. std::string result;
  19702. char buf[4];
  19703. ssize_t n;
  19704. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19705. result.append(buf, static_cast<size_t>(n));
  19706. EXPECT_EQ("Hello World!", result);
  19707. }
  19708. TEST_F(OpenStreamTest, DefaultHeaders) {
  19709. Client cli("127.0.0.1", port_);
  19710. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19711. {
  19712. auto handle = cli.open_stream("GET", "/echo-headers");
  19713. ASSERT_TRUE(handle.is_valid());
  19714. auto body = read_all(handle);
  19715. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19716. std::string::npos);
  19717. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19718. std::string::npos);
  19719. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19720. }
  19721. // open_stream POST with body and no explicit content_type should NOT add
  19722. // text/plain Content-Type (behavior differs from non-streaming path), but
  19723. // should include Content-Length
  19724. {
  19725. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19726. ASSERT_TRUE(handle.is_valid());
  19727. auto body = read_all(handle);
  19728. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19729. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19730. }
  19731. // open_stream POST with explicit Content-Type should preserve it
  19732. {
  19733. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19734. {{"Content-Type", "application/custom"}},
  19735. "{}", "application/custom");
  19736. ASSERT_TRUE(handle.is_valid());
  19737. auto body = read_all(handle);
  19738. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19739. }
  19740. // User-specified User-Agent must not be overwritten for stream API
  19741. {
  19742. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19743. {{"User-Agent", "MyAgent/1.2"}});
  19744. ASSERT_TRUE(handle.is_valid());
  19745. auto body = read_all(handle);
  19746. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19747. }
  19748. }
  19749. TEST_F(OpenStreamTest, Large) {
  19750. Client cli("127.0.0.1", port_);
  19751. auto handle = cli.open_stream("GET", "/large");
  19752. EXPECT_EQ(10000u, read_all(handle).size());
  19753. }
  19754. TEST_F(OpenStreamTest, ConnectionError) {
  19755. Client cli("127.0.0.1", 9999);
  19756. auto handle = cli.open_stream("GET", "/hello");
  19757. EXPECT_FALSE(handle.is_valid());
  19758. }
  19759. TEST_F(OpenStreamTest, Chunked) {
  19760. Client cli("127.0.0.1", port_);
  19761. auto handle = cli.open_stream("GET", "/chunked");
  19762. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19763. "Transfer-Encoding") == "chunked");
  19764. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19765. }
  19766. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19767. Client cli("127.0.0.1", port_);
  19768. auto handle =
  19769. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19770. ASSERT_TRUE(handle.is_valid());
  19771. // Consume body to allow trailers to be received/parsed
  19772. auto body = read_all(handle);
  19773. // Explicitly parse trailers (ensure trailers are available for assertion)
  19774. handle.parse_trailers_if_needed();
  19775. EXPECT_EQ(std::string("123456789"), body);
  19776. // The response should include a Trailer header declaring both names
  19777. ASSERT_TRUE(handle.response);
  19778. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19779. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19780. handle.response->get_header_value("Trailer"));
  19781. // Prohibited trailer must not be present
  19782. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19783. // Allowed trailer should be present
  19784. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19785. EXPECT_EQ(std::string("yes"),
  19786. handle.response->get_trailer_value("X-Allowed"));
  19787. // Verify trailers are NOT present as regular headers
  19788. EXPECT_EQ(std::string(""),
  19789. handle.response->get_header_value("Content-Length"));
  19790. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19791. }
  19792. // Accepts one connection on an OS-assigned port, which it hands over through
  19793. // port_promise, reads the request head and sends back response. after_send,
  19794. // if given, runs on the connection before it is closed.
  19795. static std::thread
  19796. serve_single_response(std::promise<int> &port_promise,
  19797. const std::string &response,
  19798. std::function<void(socket_t)> after_send = nullptr) {
  19799. return std::thread([&port_promise, response, after_send] {
  19800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19801. default_socket_options(srv);
  19802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19804. sockaddr_in addr{};
  19805. addr.sin_family = AF_INET;
  19806. addr.sin_port = htons(0); // Let OS assign a free port
  19807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19808. int opt = 1;
  19809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19810. #ifdef _WIN32
  19811. reinterpret_cast<const char *>(&opt),
  19812. #else
  19813. &opt,
  19814. #endif
  19815. sizeof(opt));
  19816. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19817. ::listen(srv, 1) != 0) {
  19818. port_promise.set_value(-1);
  19819. detail::close_socket(srv);
  19820. return;
  19821. }
  19822. socklen_t addr_len = sizeof(addr);
  19823. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19824. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19825. sockaddr_in cli_addr{};
  19826. socklen_t cli_len = sizeof(cli_addr);
  19827. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19828. if (cli != INVALID_SOCKET) {
  19829. // Read the complete HTTP request (until the blank line that terminates
  19830. // headers) before sending the response. If the server closes the socket
  19831. // while the client's request data is still unread in the kernel receive
  19832. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19833. // connection on both sides: it discards the client's receive buffer
  19834. // (which already holds our response) and causes any in-progress write on
  19835. // the client to fail with ECONNRESET. Reading all request data first
  19836. // ensures close() emits a graceful FIN.
  19837. {
  19838. char rbuf[256];
  19839. std::string req;
  19840. while (req.find("\r\n\r\n") == std::string::npos) {
  19841. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19842. if (n <= 0) { break; }
  19843. req.append(rbuf, static_cast<size_t>(n));
  19844. }
  19845. }
  19846. ::send(cli,
  19847. #ifdef _WIN32
  19848. static_cast<const char *>(response.c_str()),
  19849. static_cast<int>(response.size()),
  19850. #else
  19851. response.c_str(), response.size(),
  19852. #endif
  19853. 0);
  19854. if (after_send) { after_send(cli); }
  19855. detail::close_socket(cli);
  19856. }
  19857. detail::close_socket(srv);
  19858. });
  19859. }
  19860. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19861. #ifndef _WIN32
  19862. signal(SIGPIPE, SIG_IGN);
  19863. #endif
  19864. std::promise<int> port_promise;
  19865. auto port_future = port_promise.get_future();
  19866. auto server_thread =
  19867. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19868. "Content-Type: text/plain\r\n"
  19869. "Content-Length: not-a-number\r\n"
  19870. "Connection: close\r\n"
  19871. "\r\n"
  19872. "hello");
  19873. auto port = port_future.get();
  19874. ASSERT_GT(port, 0);
  19875. Client cli("127.0.0.1", port);
  19876. auto handle = cli.open_stream("GET", "/");
  19877. EXPECT_FALSE(handle.is_valid());
  19878. server_thread.join();
  19879. }
  19880. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19881. #ifndef _WIN32
  19882. signal(SIGPIPE, SIG_IGN);
  19883. #endif
  19884. std::promise<int> port_promise;
  19885. auto port_future = port_promise.get_future();
  19886. auto server_thread = serve_single_response(
  19887. port_promise, "HTTP/1.1 200 OK\r\n"
  19888. "Content-Type: text/plain\r\n"
  19889. "Content-Length: 99999999999999999999999999\r\n"
  19890. "Connection: close\r\n"
  19891. "\r\n"
  19892. "hello");
  19893. auto port = port_future.get();
  19894. ASSERT_GT(port, 0);
  19895. // Historically std::stoull would throw std::out_of_range here and crash
  19896. // the process, then parsing silently clamped to a bogus framing length and
  19897. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19898. // so the stream fails to open, matching the not-a-number case above. The
  19899. // process still must NOT terminate.
  19900. Client cli("127.0.0.1", port);
  19901. auto handle = cli.open_stream("GET", "/");
  19902. EXPECT_FALSE(handle.is_valid());
  19903. server_thread.join();
  19904. }
  19905. // Serves `response` to the single request `fn` makes with a fresh client.
  19906. template <typename Fn>
  19907. static void with_single_response(const std::string &response, Fn fn) {
  19908. #ifndef _WIN32
  19909. signal(SIGPIPE, SIG_IGN);
  19910. #endif
  19911. std::promise<int> port_promise;
  19912. auto port_future = port_promise.get_future();
  19913. auto server_thread = serve_single_response(port_promise, response);
  19914. auto se = detail::scope_exit([&] { server_thread.join(); });
  19915. auto port = port_future.get();
  19916. ASSERT_GT(port, 0);
  19917. Client cli("127.0.0.1", port);
  19918. fn(cli);
  19919. }
  19920. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19921. // Neither Content-Length nor chunked: the body ends at the close
  19922. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19923. "Connection: close\r\n"
  19924. "\r\n"
  19925. "hello";
  19926. with_single_response(close_delimited, [](Client &cli) {
  19927. auto handle = cli.open_stream("GET", "/");
  19928. ASSERT_TRUE(handle.is_valid());
  19929. EXPECT_EQ("hello", read_all(handle));
  19930. EXPECT_FALSE(handle.has_read_error());
  19931. });
  19932. // A close before the end of the Content-Length is still an error
  19933. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19934. "Content-Length: 10\r\n"
  19935. "\r\n"
  19936. "hello";
  19937. with_single_response(short_content_length, [](Client &cli) {
  19938. auto handle = cli.open_stream("GET", "/");
  19939. ASSERT_TRUE(handle.is_valid());
  19940. read_all(handle);
  19941. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19942. });
  19943. // So is a close before the last chunk
  19944. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19945. "Transfer-Encoding: chunked\r\n"
  19946. "\r\n"
  19947. "5\r\nhello\r\n";
  19948. with_single_response(short_chunked, [](Client &cli) {
  19949. auto handle = cli.open_stream("GET", "/");
  19950. ASSERT_TRUE(handle.is_valid());
  19951. read_all(handle);
  19952. EXPECT_TRUE(handle.has_read_error());
  19953. });
  19954. }
  19955. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19956. const char *responses[] = {
  19957. "HTTP/1.1 103 Early Hints\r\n"
  19958. "Link: </style.css>; rel=preload\r\n"
  19959. "\r\n"
  19960. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19961. "HTTP/1.1 100 Continue\r\n"
  19962. "X-Note: interim\r\n"
  19963. "\r\n"
  19964. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19965. };
  19966. for (auto response : responses) {
  19967. with_single_response(response, [](Client &cli) {
  19968. auto res = cli.Get("/");
  19969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19970. EXPECT_EQ(StatusCode::OK_200, res->status);
  19971. EXPECT_EQ("ok", res->body);
  19972. });
  19973. }
  19974. }
  19975. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19976. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19977. const std::string final_response =
  19978. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19979. std::string interims;
  19980. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19981. interims += interim;
  19982. }
  19983. with_single_response(interims + final_response, [](Client &cli) {
  19984. auto res = cli.Get("/");
  19985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19986. EXPECT_EQ("ok", res->body);
  19987. });
  19988. with_single_response(interims + interim + final_response, [](Client &cli) {
  19989. auto res = cli.Get("/");
  19990. ASSERT_FALSE(res);
  19991. EXPECT_EQ(Error::Read, res.error());
  19992. });
  19993. }
  19994. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19995. #ifndef _WIN32
  19996. signal(SIGPIPE, SIG_IGN);
  19997. #endif
  19998. // The server answers the head without asking for the body. Bytes it then
  19999. // reads on the connection would be taken for the body the request declared.
  20000. auto closed_by_client = false;
  20001. std::promise<int> port_promise;
  20002. auto server_thread = serve_single_response(
  20003. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20004. [&](socket_t sock) {
  20005. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20006. char buf[256];
  20007. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20008. });
  20009. Client cli("127.0.0.1", port_promise.get_future().get());
  20010. cli.set_keep_alive(true);
  20011. cli.set_read_timeout(1, 0);
  20012. // Long enough for the client to send Expect: 100-continue.
  20013. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20015. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20016. cli.Get("/second");
  20017. server_thread.join();
  20018. EXPECT_TRUE(closed_by_client);
  20019. }
  20020. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20021. // Long enough for the client to send Expect: 100-continue
  20022. with_single_response(
  20023. "HTTP/1.1 103 Early Hints\r\n"
  20024. "Link: </style.css>; rel=preload\r\n"
  20025. "\r\n"
  20026. "HTTP/1.1 401 Unauthorized\r\n"
  20027. "Content-Length: 0\r\n\r\n",
  20028. [](Client &cli) {
  20029. cli.set_read_timeout(2, 0);
  20030. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20033. });
  20034. }
  20035. #ifdef CPPHTTPLIB_SSL_ENABLED
  20036. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20037. #ifndef _WIN32
  20038. signal(SIGPIPE, SIG_IGN);
  20039. #endif
  20040. auto reused = false;
  20041. std::promise<int> port_promise;
  20042. auto server_thread = serve_single_response(
  20043. port_promise,
  20044. "HTTP/1.1 401 Unauthorized\r\n"
  20045. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20046. "Content-Length: 0\r\n\r\n",
  20047. [&](socket_t sock) {
  20048. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20049. char buf[256];
  20050. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20051. });
  20052. Client cli("127.0.0.1", port_promise.get_future().get());
  20053. cli.set_keep_alive(true);
  20054. cli.set_digest_auth("user", "pass");
  20055. cli.set_read_timeout(1, 0);
  20056. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20057. server_thread.join();
  20058. EXPECT_FALSE(reused);
  20059. }
  20060. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20061. // Any other answer to CONNECT would read as the origin's response.
  20062. struct {
  20063. const char *response;
  20064. bool passed_on;
  20065. } cases[] = {
  20066. {"HTTP/1.1 201 Created\r\n"
  20067. "Set-Cookie: session=from-proxy\r\n"
  20068. "Content-Length: 0\r\n\r\n",
  20069. false},
  20070. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20071. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20072. "Content-Length: 0\r\n\r\n",
  20073. true},
  20074. };
  20075. for (const auto &c : cases) {
  20076. std::promise<int> port_promise;
  20077. auto server_thread = serve_single_response(port_promise, c.response);
  20078. SSLClient cli("example.com", 443);
  20079. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20080. auto res = cli.Get("/");
  20081. server_thread.join();
  20082. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20083. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20084. if (res) {
  20085. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20086. }
  20087. }
  20088. }
  20089. #endif
  20090. // Records the client's error logger calls as "error METHOD path", or
  20091. // "error null" for a call without a request
  20092. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20093. return [&log](const Error &err, const Request *req) {
  20094. log.push_back(to_string(err) + " " +
  20095. (req ? req->method + " " + req->path : "null"));
  20096. };
  20097. }
  20098. // A failed request is reported once, with the request the caller made
  20099. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20100. Server svr;
  20101. svr.Get("/big", [](const Request &, Response &res) {
  20102. res.set_content(std::string(100000, 'b'), "text/plain");
  20103. });
  20104. auto port = svr.bind_to_any_port(HOST);
  20105. std::thread t([&]() { svr.listen_after_bind(); });
  20106. auto se = detail::scope_exit([&] {
  20107. svr.stop();
  20108. t.join();
  20109. });
  20110. svr.wait_until_ready();
  20111. Client cli(HOST, port);
  20112. std::vector<std::string> log;
  20113. cli.set_error_logger(record_errors(log));
  20114. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20115. cli.Get("/big", [](const char *, size_t) { return false; });
  20116. EXPECT_EQ(expected, log);
  20117. log.clear();
  20118. cli.Get("/big", [](size_t, size_t) { return false; });
  20119. EXPECT_EQ(expected, log);
  20120. }
  20121. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20122. // Fails while the body is read
  20123. auto broken = [](const Request &, Response &res) {
  20124. res.set_content_provider(10, "text/plain",
  20125. [](size_t, size_t, DataSink &) { return false; });
  20126. };
  20127. Server other;
  20128. other.Get("/broken", broken);
  20129. auto other_port = other.bind_to_any_port(HOST);
  20130. std::thread other_t([&]() { other.listen_after_bind(); });
  20131. auto other_se = detail::scope_exit([&] {
  20132. other.stop();
  20133. other_t.join();
  20134. });
  20135. other.wait_until_ready();
  20136. Server svr;
  20137. svr.Get("/broken", broken);
  20138. svr.Get("/same-origin",
  20139. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20140. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20141. res.set_redirect("http://" + std::string(HOST) + ":" +
  20142. std::to_string(other_port) + "/broken");
  20143. });
  20144. auto port = svr.bind_to_any_port(HOST);
  20145. std::thread t([&]() { svr.listen_after_bind(); });
  20146. auto se = detail::scope_exit([&] {
  20147. svr.stop();
  20148. t.join();
  20149. });
  20150. svr.wait_until_ready();
  20151. Client cli(HOST, port);
  20152. cli.set_follow_location(true);
  20153. std::vector<std::string> log;
  20154. cli.set_error_logger(record_errors(log));
  20155. for (auto path : {"/same-origin", "/cross-origin"}) {
  20156. log.clear();
  20157. auto res = cli.Get(path);
  20158. ASSERT_FALSE(res);
  20159. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20160. log);
  20161. }
  20162. }
  20163. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20164. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20165. std::vector<std::string> log;
  20166. cli.set_error_logger(record_errors(log));
  20167. auto handle = cli.open_stream("GET", "/x");
  20168. EXPECT_FALSE(handle.is_valid());
  20169. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20170. log);
  20171. });
  20172. }
  20173. #ifdef CPPHTTPLIB_SSL_ENABLED
  20174. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20175. // Not a TLS server, so the handshake fails. It waits for a request line in
  20176. // the handshake bytes, so a short read timeout lets it close quickly.
  20177. Server svr;
  20178. svr.set_read_timeout(0, 100000);
  20179. svr.Get("/x", [](const Request &, Response &res) {
  20180. res.set_content("x", "text/plain");
  20181. });
  20182. auto port = svr.bind_to_any_port(HOST);
  20183. std::thread t([&]() { svr.listen_after_bind(); });
  20184. auto se = detail::scope_exit([&] {
  20185. svr.stop();
  20186. t.join();
  20187. });
  20188. svr.wait_until_ready();
  20189. std::vector<std::string> log;
  20190. SSLClient cli(HOST, port);
  20191. cli.enable_server_certificate_verification(false);
  20192. cli.set_error_logger(record_errors(log));
  20193. auto res = cli.Get("/x");
  20194. ASSERT_FALSE(res);
  20195. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20196. log.clear();
  20197. auto handle = cli.open_stream("GET", "/x");
  20198. EXPECT_FALSE(handle.is_valid());
  20199. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20200. log.clear();
  20201. SSLClient no_ca(HOST, port);
  20202. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20203. no_ca.set_error_logger(record_errors(log));
  20204. res = no_ca.Get("/x");
  20205. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20206. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20207. }
  20208. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20209. #ifndef _WIN32
  20210. signal(SIGPIPE, SIG_IGN);
  20211. #endif
  20212. // Refused, answered with a challenge, or closed without an answer
  20213. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20214. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20215. "Content-Length: 0\r\n\r\n",
  20216. ""}) {
  20217. std::promise<int> port_promise;
  20218. auto server_thread = serve_single_response(port_promise, response);
  20219. SSLClient cli("example.com", 443);
  20220. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20221. std::vector<std::string> log;
  20222. cli.set_error_logger(record_errors(log));
  20223. auto res = cli.Get("/");
  20224. server_thread.join();
  20225. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20226. << response;
  20227. }
  20228. }
  20229. #endif
  20230. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20231. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20232. // the chunked coding and drop Content-Length, so a front-end that trusts
  20233. // Content-Length would disagree about where the body ends (response
  20234. // smuggling). The client must reject such a response.
  20235. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20236. for (const char *te : {"chunked", "gzip, chunked"}) {
  20237. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20238. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20239. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20240. "5\r\nhello\r\n0\r\n\r\n";
  20241. with_single_response(response, [&](Client &cli) {
  20242. auto res = cli.Get("/");
  20243. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20244. EXPECT_EQ(Error::Read, res.error()) << te;
  20245. });
  20246. with_single_response(response, [&](Client &cli) {
  20247. auto handle = cli.open_stream("GET", "/");
  20248. EXPECT_FALSE(handle.is_valid()) << te;
  20249. EXPECT_EQ(Error::Read, handle.error) << te;
  20250. });
  20251. }
  20252. }
  20253. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20254. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20255. // closing the connection (unlike a request, which must be rejected).
  20256. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20257. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20258. "Transfer-Encoding: chunked\r\n"
  20259. "Connection: close\r\n"
  20260. "\r\n"
  20261. "5\r\nhello\r\n0\r\n\r\n",
  20262. "HTTP/1.1 200 OK\r\n"
  20263. "Transfer-Encoding: gzip\r\n"
  20264. "Connection: close\r\n"
  20265. "\r\n"
  20266. "hello"}) {
  20267. with_single_response(response, [&](Client &cli) {
  20268. auto res = cli.Get("/");
  20269. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20270. EXPECT_EQ("hello", res->body);
  20271. });
  20272. with_single_response(response, [&](Client &cli) {
  20273. auto handle = cli.open_stream("GET", "/");
  20274. ASSERT_TRUE(handle.is_valid()) << response;
  20275. EXPECT_EQ("hello", read_all(handle));
  20276. });
  20277. }
  20278. }
  20279. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20280. // framing headers describe nothing to read and must not be rejected.
  20281. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20282. const std::string framing = "Content-Length: 5\r\n"
  20283. "Transfer-Encoding: chunked\r\n"
  20284. "Connection: close\r\n"
  20285. "\r\n";
  20286. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20287. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20288. });
  20289. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20290. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20291. });
  20292. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20293. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20294. with_single_response(response, [&](Client &cli) {
  20295. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20296. });
  20297. with_single_response(response, [&](Client &cli) {
  20298. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20299. });
  20300. }
  20301. }
  20302. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20303. // header section, so a stream opened on one has nothing to read, whatever
  20304. // framing or coding headers it carries.
  20305. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20306. struct Case {
  20307. const char *method;
  20308. const char *status;
  20309. };
  20310. // A reader of the declared body reports an early close when nothing
  20311. // follows, and hands back what does.
  20312. struct Framing {
  20313. const char *headers;
  20314. const char *after;
  20315. };
  20316. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20317. Case{"GET", "304 Not Modified"}}) {
  20318. for (const auto &f :
  20319. {Framing{"Content-Length: 5\r\n", ""},
  20320. Framing{"Content-Length: 5\r\n", "hello"},
  20321. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20322. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20323. // Not decoded, so a build without Brotli opens it too
  20324. Framing{"Content-Encoding: br\r\n", ""}}) {
  20325. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20326. "Connection: close\r\n"
  20327. "\r\n" +
  20328. f.after;
  20329. with_single_response(response, [&](Client &cli) {
  20330. auto handle = cli.open_stream(c.method, "/");
  20331. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20332. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20333. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20334. });
  20335. }
  20336. }
  20337. }
  20338. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20339. // response, is faulty framing, so the connection is not reused after it.
  20340. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20341. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20342. "Content-Length: 0\r\n"
  20343. "Transfer-Encoding: chunked\r\n"
  20344. "\r\n"
  20345. "5\r\nhello\r\n0\r\n\r\n",
  20346. "HTTP/1.0 200 Connection established\r\n"
  20347. "Connection: keep-alive\r\n"
  20348. "Transfer-Encoding: chunked\r\n"
  20349. "\r\n"
  20350. "5\r\nhello\r\n0\r\n\r\n"}) {
  20351. with_single_response(response, [&](Client &cli) {
  20352. cli.set_keep_alive(true);
  20353. auto res = cli.Get("/");
  20354. ASSERT_TRUE(res) << response;
  20355. EXPECT_EQ("hello", res->body);
  20356. EXPECT_FALSE(cli.is_socket_open()) << response;
  20357. });
  20358. }
  20359. }
  20360. // A payload max length of 0 means no limit, however the body is framed.
  20361. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20362. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20363. "Transfer-Encoding: chunked\r\n"
  20364. "\r\n"
  20365. "5\r\nhello\r\n0\r\n\r\n",
  20366. "HTTP/1.1 200 OK\r\n"
  20367. "Connection: close\r\n"
  20368. "\r\n"
  20369. "hello"}) {
  20370. with_single_response(response, [&](Client &cli) {
  20371. cli.set_payload_max_length(0);
  20372. auto res = cli.Get("/");
  20373. ASSERT_TRUE(res) << response;
  20374. EXPECT_EQ("hello", res->body) << response;
  20375. });
  20376. }
  20377. }
  20378. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20379. Server svr;
  20380. svr.set_payload_max_length(0);
  20381. svr.Post("/echo", [](const Request &req, Response &res) {
  20382. res.set_content(req.body, "text/plain");
  20383. });
  20384. auto port = svr.bind_to_any_port(HOST);
  20385. thread t = thread([&] { svr.listen_after_bind(); });
  20386. auto se = detail::scope_exit([&] {
  20387. svr.stop();
  20388. t.join();
  20389. ASSERT_FALSE(svr.is_running());
  20390. });
  20391. svr.wait_until_ready();
  20392. Client cli(HOST, port);
  20393. auto res = cli.Post(
  20394. "/echo",
  20395. [](size_t /*offset*/, DataSink &sink) {
  20396. sink.write("hello", 5);
  20397. sink.done();
  20398. return true;
  20399. },
  20400. "text/plain");
  20401. ASSERT_TRUE(res);
  20402. EXPECT_EQ(StatusCode::OK_200, res->status);
  20403. EXPECT_EQ("hello", res->body);
  20404. }
  20405. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20406. TEST_F(OpenStreamTest, Gzip) {
  20407. Client cli("127.0.0.1", port_);
  20408. auto handle = cli.open_stream("GET", "/compressible", {},
  20409. {{"Accept-Encoding", "gzip"}});
  20410. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20411. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20412. }
  20413. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20414. Client cli("127.0.0.1", port_);
  20415. auto handle =
  20416. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20417. {{"Accept-Encoding", "gzip"}});
  20418. ASSERT_TRUE(handle.is_valid());
  20419. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20420. EXPECT_EQ("123456789", read_all(handle));
  20421. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20422. }
  20423. #endif
  20424. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20425. TEST_F(OpenStreamTest, Brotli) {
  20426. Client cli("127.0.0.1", port_);
  20427. auto handle =
  20428. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20429. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20430. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20431. }
  20432. #endif
  20433. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20434. TEST_F(OpenStreamTest, Zstd) {
  20435. Client cli("127.0.0.1", port_);
  20436. auto handle = cli.open_stream("GET", "/compressible", {},
  20437. {{"Accept-Encoding", "zstd"}});
  20438. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20439. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20440. }
  20441. #endif
  20442. #ifdef CPPHTTPLIB_SSL_ENABLED
  20443. class SSLOpenStreamTest : public ::testing::Test {
  20444. protected:
  20445. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20446. void SetUp() override {
  20447. svr_.Get("/hello", [](const Request &, Response &res) {
  20448. res.set_content("Hello SSL World!", "text/plain");
  20449. });
  20450. svr_.Get("/chunked", [](const Request &, Response &res) {
  20451. res.set_chunked_content_provider("text/plain",
  20452. [](size_t offset, DataSink &sink) {
  20453. if (offset < 15) {
  20454. sink.write("chunk", 5);
  20455. return true;
  20456. }
  20457. sink.done();
  20458. return true;
  20459. });
  20460. });
  20461. svr_.Post("/echo", [](const Request &req, Response &res) {
  20462. res.set_content(req.body, req.get_header_value("Content-Type"));
  20463. });
  20464. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20465. std::string body = req.body;
  20466. res.set_chunked_content_provider(
  20467. "text/plain", [body](size_t offset, DataSink &sink) {
  20468. if (offset < body.size()) {
  20469. sink.write(body.data() + offset, body.size() - offset);
  20470. }
  20471. sink.done();
  20472. return true;
  20473. });
  20474. });
  20475. port_ = svr_.bind_to_any_port("127.0.0.1");
  20476. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20477. svr_.wait_until_ready();
  20478. }
  20479. void TearDown() override {
  20480. svr_.stop();
  20481. if (thread_.joinable()) thread_.join();
  20482. }
  20483. SSLServer svr_;
  20484. std::thread thread_;
  20485. int port_ = 0;
  20486. };
  20487. TEST_F(SSLOpenStreamTest, Basic) {
  20488. SSLClient cli("127.0.0.1", port_);
  20489. cli.enable_server_certificate_verification(false);
  20490. auto handle = cli.open_stream("GET", "/hello");
  20491. ASSERT_TRUE(handle.is_valid());
  20492. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20493. }
  20494. TEST_F(SSLOpenStreamTest, Chunked) {
  20495. SSLClient cli("127.0.0.1", port_);
  20496. cli.enable_server_certificate_verification(false);
  20497. auto handle = cli.open_stream("GET", "/chunked");
  20498. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20499. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20500. "Transfer-Encoding") == "chunked");
  20501. auto body = read_all(handle);
  20502. EXPECT_EQ("chunkchunkchunk", body);
  20503. }
  20504. TEST_F(SSLOpenStreamTest, Post) {
  20505. SSLClient cli("127.0.0.1", port_);
  20506. cli.enable_server_certificate_verification(false);
  20507. auto handle =
  20508. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20509. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20510. EXPECT_EQ(200, handle.response->status);
  20511. auto body = read_all(handle);
  20512. EXPECT_EQ("Hello SSL POST", body);
  20513. }
  20514. TEST_F(SSLOpenStreamTest, PostChunked) {
  20515. SSLClient cli("127.0.0.1", port_);
  20516. cli.enable_server_certificate_verification(false);
  20517. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20518. "Chunked SSL Data", "text/plain");
  20519. ASSERT_TRUE(handle.is_valid());
  20520. EXPECT_EQ(200, handle.response->status);
  20521. auto body = read_all(handle);
  20522. EXPECT_EQ("Chunked SSL Data", body);
  20523. }
  20524. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20525. // Content-Length is terminated by the server closing the connection. When the
  20526. // SSL peer sends a close_notify after the body, the client must treat it as a
  20527. // clean EOF and return a successful response rather than an error.
  20528. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20530. ASSERT_TRUE(svr.is_valid());
  20531. svr.set_keep_alive_max_count(1);
  20532. const std::string expected_body = "Hello from connection-close response!";
  20533. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20534. res.set_content_provider("text/plain",
  20535. [&](size_t offset, DataSink &sink) -> bool {
  20536. if (offset < expected_body.size()) {
  20537. sink.write(expected_body.data() + offset,
  20538. expected_body.size() - offset);
  20539. }
  20540. sink.done();
  20541. return true;
  20542. });
  20543. });
  20544. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20545. auto se = detail::scope_exit([&] {
  20546. svr.stop();
  20547. listen_thread.join();
  20548. ASSERT_FALSE(svr.is_running());
  20549. });
  20550. svr.wait_until_ready();
  20551. SSLClient cli(HOST, PORT);
  20552. cli.enable_server_certificate_verification(false);
  20553. auto res = cli.Get("/no-content-length");
  20554. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20555. EXPECT_EQ(StatusCode::OK_200, res->status);
  20556. EXPECT_EQ(expected_body, res->body);
  20557. }
  20558. #endif // CPPHTTPLIB_SSL_ENABLED
  20559. //==============================================================================
  20560. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20561. // results for various scenarios.
  20562. //==============================================================================
  20563. TEST(ParityTest, GetVsOpenStream) {
  20564. Server svr;
  20565. const std::string path = "/parity";
  20566. const std::string content = "Parity test content: hello world";
  20567. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20568. res.set_content(content, "text/plain");
  20569. });
  20570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20571. auto se = detail::scope_exit([&] {
  20572. svr.stop();
  20573. t.join();
  20574. ASSERT_FALSE(svr.is_running());
  20575. });
  20576. svr.wait_until_ready();
  20577. Client cli(HOST, PORT);
  20578. // Non-stream path
  20579. auto r1 = cli.Get(path);
  20580. ASSERT_TRUE(r1);
  20581. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20582. // Stream path
  20583. auto h = cli.open_stream("GET", path);
  20584. ASSERT_TRUE(h.is_valid());
  20585. EXPECT_EQ(r1->body, read_all(h));
  20586. }
  20587. // Helper to compress data with provided compressor type T
  20588. template <typename Compressor>
  20589. static std::string compress_payload_for_parity(const std::string &in) {
  20590. std::string out;
  20591. Compressor compressor;
  20592. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20593. [&](const char *data, size_t n) {
  20594. out.append(data, n);
  20595. return true;
  20596. });
  20597. EXPECT_TRUE(ok);
  20598. return out;
  20599. }
  20600. // Helper function for compression parity tests
  20601. template <typename Compressor>
  20602. static void test_compression_parity(const std::string &original,
  20603. const std::string &path,
  20604. const std::string &encoding) {
  20605. const std::string compressed =
  20606. compress_payload_for_parity<Compressor>(original);
  20607. Server svr;
  20608. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20609. res.set_content(compressed, "application/octet-stream");
  20610. res.set_header("Content-Encoding", encoding);
  20611. });
  20612. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20613. auto se = detail::scope_exit([&] {
  20614. svr.stop();
  20615. t.join();
  20616. ASSERT_FALSE(svr.is_running());
  20617. });
  20618. svr.wait_until_ready();
  20619. Client cli(HOST, PORT);
  20620. // Non-streaming
  20621. {
  20622. auto res = cli.Get(path);
  20623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20624. EXPECT_EQ(StatusCode::OK_200, res->status);
  20625. EXPECT_EQ(original, res->body);
  20626. }
  20627. // Streaming
  20628. {
  20629. auto h = cli.open_stream("GET", path);
  20630. ASSERT_TRUE(h.is_valid());
  20631. EXPECT_EQ(original, read_all(h));
  20632. }
  20633. }
  20634. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20635. TEST(ParityTest, Gzip) {
  20636. test_compression_parity<detail::gzip_compressor>(
  20637. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20638. }
  20639. #endif
  20640. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20641. TEST(ParityTest, Brotli) {
  20642. test_compression_parity<detail::brotli_compressor>(
  20643. "Hello, brotli parity test payload", "/parity-br", "br");
  20644. }
  20645. #endif
  20646. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20647. TEST(ParityTest, Zstd) {
  20648. test_compression_parity<detail::zstd_compressor>(
  20649. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20650. }
  20651. #endif
  20652. //==============================================================================
  20653. // New Stream API Tests
  20654. //==============================================================================
  20655. inline std::string read_body(httplib::stream::Result &result) {
  20656. std::string body;
  20657. while (result.next()) {
  20658. body.append(result.data(), result.size());
  20659. }
  20660. return body;
  20661. }
  20662. TEST(ClientConnectionTest, Basic) {
  20663. httplib::ClientConnection conn;
  20664. EXPECT_FALSE(conn.is_open());
  20665. conn.sock = 1;
  20666. EXPECT_TRUE(conn.is_open());
  20667. httplib::ClientConnection conn2(std::move(conn));
  20668. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20669. conn2.sock = INVALID_SOCKET;
  20670. }
  20671. // Unified test server for all stream::* tests
  20672. class StreamApiTest : public ::testing::Test {
  20673. protected:
  20674. void SetUp() override {
  20675. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20676. res.set_content("Hello World!", "text/plain");
  20677. });
  20678. svr_.Get("/echo-params",
  20679. [](const httplib::Request &req, httplib::Response &res) {
  20680. std::string r;
  20681. for (const auto &p : req.params) {
  20682. if (!r.empty()) r += "&";
  20683. r += p.first + "=" + p.second;
  20684. }
  20685. res.set_content(r, "text/plain");
  20686. });
  20687. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20688. res.set_content(req.body, req.get_header_value("Content-Type"));
  20689. });
  20690. svr_.Post("/echo-headers",
  20691. [](const httplib::Request &req, httplib::Response &res) {
  20692. std::string r;
  20693. for (const auto &h : req.headers)
  20694. r += h.first + ": " + h.second + "\n";
  20695. res.set_content(r, "text/plain");
  20696. });
  20697. svr_.Post("/echo-params",
  20698. [](const httplib::Request &req, httplib::Response &res) {
  20699. std::string r = "params:";
  20700. for (const auto &p : req.params)
  20701. r += p.first + "=" + p.second + ";";
  20702. res.set_content(r + " body:" + req.body, "text/plain");
  20703. });
  20704. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20705. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20706. });
  20707. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20708. res.set_content("PUT:" + req.body, "text/plain");
  20709. });
  20710. svr_.Patch("/echo",
  20711. [](const httplib::Request &req, httplib::Response &res) {
  20712. res.set_content("PATCH:" + req.body, "text/plain");
  20713. });
  20714. svr_.Delete(
  20715. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20716. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20717. "text/plain");
  20718. });
  20719. svr_.Get("/head-test",
  20720. [](const httplib::Request &, httplib::Response &res) {
  20721. res.set_content("body for HEAD", "text/plain");
  20722. });
  20723. svr_.Options("/options",
  20724. [](const httplib::Request &, httplib::Response &res) {
  20725. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20726. });
  20727. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20728. svr_.wait_until_ready();
  20729. }
  20730. void TearDown() override {
  20731. svr_.stop();
  20732. if (thread_.joinable()) thread_.join();
  20733. }
  20734. httplib::Server svr_;
  20735. std::thread thread_;
  20736. };
  20737. // stream::Get tests
  20738. TEST_F(StreamApiTest, GetBasic) {
  20739. httplib::Client cli(HOST, PORT);
  20740. auto result = httplib::stream::Get(cli, "/hello");
  20741. ASSERT_TRUE(result.is_valid());
  20742. EXPECT_EQ(200, result.status());
  20743. EXPECT_EQ("Hello World!", read_body(result));
  20744. }
  20745. TEST_F(StreamApiTest, GetWithParams) {
  20746. httplib::Client cli(HOST, PORT);
  20747. httplib::Params params{{"foo", "bar"}};
  20748. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20749. ASSERT_TRUE(result.is_valid());
  20750. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20751. }
  20752. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20753. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20754. httplib::Client cli(HOST, PORT);
  20755. cli.set_payload_max_length(0);
  20756. auto result = httplib::stream::Get(cli, "/hello");
  20757. ASSERT_TRUE(result.is_valid());
  20758. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20759. EXPECT_EQ("Hello World!", read_body(result));
  20760. }
  20761. #endif
  20762. TEST_F(StreamApiTest, GetConnectionError) {
  20763. httplib::Client cli(HOST, 9999);
  20764. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20765. }
  20766. TEST_F(StreamApiTest, Get404) {
  20767. httplib::Client cli(HOST, PORT);
  20768. auto result = httplib::stream::Get(cli, "/nonexistent");
  20769. EXPECT_TRUE(result.is_valid());
  20770. EXPECT_EQ(404, result.status());
  20771. }
  20772. // stream::Post tests
  20773. TEST_F(StreamApiTest, PostBasic) {
  20774. httplib::Client cli(HOST, PORT);
  20775. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20776. "application/json");
  20777. ASSERT_TRUE(result.is_valid());
  20778. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20779. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20780. }
  20781. TEST_F(StreamApiTest, PostWithHeaders) {
  20782. httplib::Client cli(HOST, PORT);
  20783. httplib::Headers headers{{"X-Custom", "value"}};
  20784. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20785. "text/plain");
  20786. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20787. }
  20788. TEST_F(StreamApiTest, PostWithParams) {
  20789. httplib::Client cli(HOST, PORT);
  20790. httplib::Params params{{"k", "v"}};
  20791. auto result =
  20792. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20793. auto body = read_body(result);
  20794. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20795. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20796. }
  20797. TEST_F(StreamApiTest, PostLarge) {
  20798. httplib::Client cli(HOST, PORT);
  20799. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20800. size_t total = 0;
  20801. while (result.next()) {
  20802. total += result.size();
  20803. }
  20804. EXPECT_EQ(100u * 1024u, total);
  20805. }
  20806. // stream::Put/Patch tests
  20807. TEST_F(StreamApiTest, PutAndPatch) {
  20808. httplib::Client cli(HOST, PORT);
  20809. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20810. EXPECT_EQ("PUT:test", read_body(put));
  20811. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20812. EXPECT_EQ("PATCH:test", read_body(patch));
  20813. }
  20814. // stream::Delete tests
  20815. TEST_F(StreamApiTest, Delete) {
  20816. httplib::Client cli(HOST, PORT);
  20817. auto del1 = httplib::stream::Delete(cli, "/resource");
  20818. EXPECT_EQ("Deleted", read_body(del1));
  20819. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20820. EXPECT_EQ("Deleted:data", read_body(del2));
  20821. }
  20822. // stream::Head/Options tests
  20823. TEST_F(StreamApiTest, HeadAndOptions) {
  20824. httplib::Client cli(HOST, PORT);
  20825. auto head = httplib::stream::Head(cli, "/head-test");
  20826. EXPECT_TRUE(head.is_valid());
  20827. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20828. auto opts = httplib::stream::Options(cli, "/options");
  20829. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20830. }
  20831. // SSL stream::* tests
  20832. #ifdef CPPHTTPLIB_SSL_ENABLED
  20833. class SSLStreamApiTest : public ::testing::Test {
  20834. protected:
  20835. void SetUp() override {
  20836. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20837. res.set_content("Hello SSL!", "text/plain");
  20838. });
  20839. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20840. res.set_content(req.body, "text/plain");
  20841. });
  20842. port_ = svr_.bind_to_any_port("127.0.0.1");
  20843. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20844. svr_.wait_until_ready();
  20845. }
  20846. void TearDown() override {
  20847. svr_.stop();
  20848. if (thread_.joinable()) thread_.join();
  20849. }
  20850. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20851. std::thread thread_;
  20852. int port_ = 0;
  20853. };
  20854. TEST_F(SSLStreamApiTest, GetAndPost) {
  20855. httplib::SSLClient cli("127.0.0.1", port_);
  20856. cli.enable_server_certificate_verification(false);
  20857. auto get = httplib::stream::Get(cli, "/hello");
  20858. EXPECT_EQ("Hello SSL!", read_body(get));
  20859. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20860. EXPECT_EQ("test", read_body(post));
  20861. }
  20862. #endif
  20863. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20864. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20865. // BodyReader
  20866. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20867. // Test that read timeout during streaming is detected
  20868. // Use a large content-length response where server delays mid-stream
  20869. Server svr;
  20870. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20871. // Send a large response with delay in the middle
  20872. res.set_content_provider(
  20873. 1000, // content_length
  20874. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20875. if (offset < 100) {
  20876. // Send first 100 bytes immediately
  20877. std::string data(100, 'A');
  20878. sink.write(data.c_str(), data.size());
  20879. return true;
  20880. }
  20881. // Then delay longer than client timeout
  20882. std::this_thread::sleep_for(std::chrono::seconds(3));
  20883. std::string data(900, 'B');
  20884. sink.write(data.c_str(), data.size());
  20885. return true;
  20886. });
  20887. });
  20888. auto port = 8091;
  20889. std::thread t([&]() { svr.listen("localhost", port); });
  20890. svr.wait_until_ready();
  20891. Client cli("localhost", port);
  20892. cli.set_read_timeout(1, 0); // 1 second timeout
  20893. auto handle = cli.open_stream("GET", "/slow-stream");
  20894. ASSERT_TRUE(handle.is_valid());
  20895. char buf[256];
  20896. ssize_t total = 0;
  20897. ssize_t n;
  20898. bool got_error = false;
  20899. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20900. total += n;
  20901. }
  20902. if (n < 0) {
  20903. got_error = true;
  20904. // Should be timeout or read error
  20905. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20906. handle.get_read_error() == Error::Read)
  20907. << "Actual error: " << to_string(handle.get_read_error());
  20908. }
  20909. // Either we got an error, or we got less data than expected
  20910. EXPECT_TRUE(got_error || total < 1000)
  20911. << "Expected timeout but got all " << total << " bytes";
  20912. svr.stop();
  20913. t.join();
  20914. }
  20915. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20916. // Test connection closed detection via BodyReader
  20917. Server svr;
  20918. std::atomic<bool> close_now{false};
  20919. svr.Get("/will-close", [&](const Request &, Response &res) {
  20920. res.set_content_provider(
  20921. 10000, // Large content_length that we won't fully send
  20922. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20923. if (offset < 100) {
  20924. std::string data(100, 'X');
  20925. sink.write(data.c_str(), data.size());
  20926. return true;
  20927. }
  20928. // Wait for signal then abort
  20929. while (!close_now) {
  20930. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20931. }
  20932. return false; // Abort - server will close connection
  20933. });
  20934. });
  20935. auto port = 8092;
  20936. std::thread t([&]() { svr.listen("localhost", port); });
  20937. svr.wait_until_ready();
  20938. Client cli("localhost", port);
  20939. auto handle = cli.open_stream("GET", "/will-close");
  20940. ASSERT_TRUE(handle.is_valid());
  20941. char buf[256];
  20942. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20943. EXPECT_GT(n, 0) << "First read should succeed";
  20944. // Signal server to close
  20945. close_now = true;
  20946. // Keep reading until error or EOF
  20947. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20948. // Keep reading
  20949. }
  20950. // Should get an error since content_length wasn't satisfied
  20951. if (n < 0) {
  20952. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20953. handle.get_read_error() == Error::Read)
  20954. << "Actual error: " << to_string(handle.get_read_error());
  20955. }
  20956. svr.stop();
  20957. t.join();
  20958. }
  20959. #ifdef CPPHTTPLIB_SSL_ENABLED
  20960. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20961. // Test that read timeout during SSL streaming is detected
  20962. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20963. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20964. res.set_content_provider(
  20965. 1000, "text/plain",
  20966. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20967. if (offset < 100) {
  20968. std::string data(100, 'A');
  20969. sink.write(data.c_str(), data.size());
  20970. return true;
  20971. }
  20972. std::this_thread::sleep_for(std::chrono::seconds(3));
  20973. std::string data(900, 'B');
  20974. sink.write(data.c_str(), data.size());
  20975. return true;
  20976. });
  20977. });
  20978. auto port = 8093;
  20979. std::thread t([&]() { svr.listen("localhost", port); });
  20980. svr.wait_until_ready();
  20981. SSLClient cli("localhost", port);
  20982. cli.enable_server_certificate_verification(false);
  20983. cli.set_read_timeout(1, 0); // 1 second timeout
  20984. auto handle = cli.open_stream("GET", "/slow-stream");
  20985. ASSERT_TRUE(handle.is_valid());
  20986. char buf[256];
  20987. ssize_t total = 0;
  20988. ssize_t n;
  20989. bool got_error = false;
  20990. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20991. total += n;
  20992. }
  20993. if (n < 0) {
  20994. got_error = true;
  20995. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20996. handle.get_read_error() == Error::Read)
  20997. << "Actual error: " << to_string(handle.get_read_error());
  20998. }
  20999. EXPECT_TRUE(got_error || total < 1000)
  21000. << "Expected timeout but got all " << total << " bytes";
  21001. svr.stop();
  21002. t.join();
  21003. }
  21004. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21005. // Test SSL connection closed detection
  21006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21007. std::atomic<bool> close_now{false};
  21008. svr.Get("/will-close", [&](const Request &, Response &res) {
  21009. res.set_content_provider(
  21010. 10000, "text/plain",
  21011. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21012. if (offset < 100) {
  21013. std::string data(100, 'X');
  21014. sink.write(data.c_str(), data.size());
  21015. return true;
  21016. }
  21017. while (!close_now) {
  21018. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21019. }
  21020. return false;
  21021. });
  21022. });
  21023. auto port = 8094;
  21024. std::thread t([&]() { svr.listen("localhost", port); });
  21025. svr.wait_until_ready();
  21026. SSLClient cli("localhost", port);
  21027. cli.enable_server_certificate_verification(false);
  21028. auto handle = cli.open_stream("GET", "/will-close");
  21029. ASSERT_TRUE(handle.is_valid());
  21030. char buf[256];
  21031. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21032. EXPECT_GT(n, 0);
  21033. // Signal server to close
  21034. close_now = true;
  21035. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21036. // Keep reading
  21037. }
  21038. if (n < 0) {
  21039. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21040. handle.get_read_error() == Error::Read)
  21041. << "Actual error: " << to_string(handle.get_read_error());
  21042. }
  21043. svr.stop();
  21044. t.join();
  21045. }
  21046. #endif
  21047. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21048. using namespace httplib;
  21049. // Create a test file
  21050. const char *fname = "etag_testfile.txt";
  21051. const char *content = "etag-content";
  21052. {
  21053. std::ofstream ofs(fname);
  21054. ofs << content;
  21055. ASSERT_TRUE(ofs.good());
  21056. }
  21057. Server svr;
  21058. svr.set_mount_point("/static", ".");
  21059. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21060. svr.wait_until_ready();
  21061. Client cli(HOST, PORT);
  21062. // First request: should get 200 with ETag header
  21063. auto res1 = cli.Get("/static/etag_testfile.txt");
  21064. ASSERT_TRUE(res1);
  21065. ASSERT_EQ(200, res1->status);
  21066. ASSERT_TRUE(res1->has_header("ETag"));
  21067. std::string etag = res1->get_header_value("ETag");
  21068. EXPECT_FALSE(etag.empty());
  21069. // Verify ETag format: W/"hex-hex"
  21070. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21071. EXPECT_EQ('W', etag[0]);
  21072. EXPECT_EQ('/', etag[1]);
  21073. EXPECT_EQ('"', etag[2]);
  21074. EXPECT_EQ('"', etag.back());
  21075. // Exact match: expect 304 Not Modified
  21076. Headers h2 = {{"If-None-Match", etag}};
  21077. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21078. ASSERT_TRUE(res2);
  21079. EXPECT_EQ(304, res2->status);
  21080. // Wildcard match: expect 304 Not Modified
  21081. Headers h3 = {{"If-None-Match", "*"}};
  21082. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21083. ASSERT_TRUE(res3);
  21084. EXPECT_EQ(304, res3->status);
  21085. // Non-matching ETag: expect 200
  21086. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21087. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21088. ASSERT_TRUE(res4);
  21089. EXPECT_EQ(200, res4->status);
  21090. // Multiple ETags with one matching: expect 304
  21091. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21092. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21093. ASSERT_TRUE(res5);
  21094. EXPECT_EQ(304, res5->status);
  21095. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21096. // that equivalent to the single comma-separated list above, so the match on
  21097. // the second line must still be found.
  21098. Headers h6;
  21099. h6.emplace("If-None-Match", "W/\"other\"");
  21100. h6.emplace("If-None-Match", etag);
  21101. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21102. ASSERT_TRUE(res6);
  21103. EXPECT_EQ(304, res6->status);
  21104. svr.stop();
  21105. t.join();
  21106. std::remove(fname);
  21107. }
  21108. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21109. using namespace httplib;
  21110. Server svr;
  21111. svr.set_mount_point("/static", ".");
  21112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21113. svr.wait_until_ready();
  21114. Client cli(HOST, PORT);
  21115. // Send If-None-Match: * to a non-existent file
  21116. Headers h = {{"If-None-Match", "*"}};
  21117. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21119. EXPECT_EQ(404, res->status);
  21120. svr.stop();
  21121. t.join();
  21122. }
  21123. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21124. using namespace httplib;
  21125. // Create a test file
  21126. const char *fname = "etag_boundary_testfile.txt";
  21127. const char *content = "boundary-test";
  21128. {
  21129. std::ofstream ofs(fname);
  21130. ofs << content;
  21131. ASSERT_TRUE(ofs.good());
  21132. }
  21133. Server svr;
  21134. svr.set_mount_point("/static", ".");
  21135. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21136. svr.wait_until_ready();
  21137. Client cli(HOST, PORT);
  21138. // Get the actual ETag
  21139. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21140. ASSERT_TRUE(res1);
  21141. ASSERT_EQ(200, res1->status);
  21142. ASSERT_TRUE(res1->has_header("ETag"));
  21143. std::string etag = res1->get_header_value("ETag");
  21144. // Test 1: Very long ETag value (longer than actual ETag)
  21145. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21146. Headers h1 = {{"If-None-Match", "W/"
  21147. "\"very-long-etag-value-that-is-much-longer-"
  21148. "than-the-actual-etag-value\""}};
  21149. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21150. ASSERT_TRUE(res2);
  21151. EXPECT_EQ(200, res2->status); // Should not match
  21152. // Test 2: Long string followed by wildcard
  21153. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21154. // string)
  21155. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21156. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21157. ASSERT_TRUE(res3);
  21158. EXPECT_EQ(304, res3->status); // Should match on "*"
  21159. // Test 3: Wildcard followed by long string
  21160. // Should match on "*" immediately and return 304
  21161. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21162. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21163. ASSERT_TRUE(res4);
  21164. EXPECT_EQ(304, res4->status); // Should match on "*"
  21165. // Test 4: Multiple long non-matching values
  21166. // Should NOT match and return 200 (test that all comparisons are safe)
  21167. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21168. "W/\"second-long-non-matching-value\", "
  21169. "W/\"third-long-non-matching-value\""}};
  21170. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21171. ASSERT_TRUE(res5);
  21172. EXPECT_EQ(200, res5->status); // Should not match
  21173. // Test 5: Single character that is not "*" (edge case)
  21174. Headers h5 = {{"If-None-Match", "X"}};
  21175. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21176. ASSERT_TRUE(res6);
  21177. EXPECT_EQ(200, res6->status); // Should not match
  21178. svr.stop();
  21179. t.join();
  21180. std::remove(fname);
  21181. }
  21182. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21183. using namespace httplib;
  21184. // Create a test file
  21185. const char *fname = "ims_testfile.txt";
  21186. const char *content = "if-modified-since-test";
  21187. {
  21188. std::ofstream ofs(fname);
  21189. ofs << content;
  21190. ASSERT_TRUE(ofs.good());
  21191. }
  21192. Server svr;
  21193. svr.set_mount_point("/static", ".");
  21194. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21195. svr.wait_until_ready();
  21196. Client cli(HOST, PORT);
  21197. // First request: should get 200 with Last-Modified header
  21198. auto res1 = cli.Get("/static/ims_testfile.txt");
  21199. ASSERT_TRUE(res1);
  21200. ASSERT_EQ(200, res1->status);
  21201. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21202. std::string last_modified = res1->get_header_value("Last-Modified");
  21203. EXPECT_FALSE(last_modified.empty());
  21204. // If-Modified-Since with same time: expect 304
  21205. Headers h2 = {{"If-Modified-Since", last_modified}};
  21206. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21207. ASSERT_TRUE(res2);
  21208. EXPECT_EQ(304, res2->status);
  21209. // If-Modified-Since with future time: expect 304
  21210. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21211. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21212. ASSERT_TRUE(res3);
  21213. EXPECT_EQ(304, res3->status);
  21214. // If-Modified-Since with past time: expect 200
  21215. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21216. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21217. ASSERT_TRUE(res4);
  21218. EXPECT_EQ(200, res4->status);
  21219. // If-None-Match takes precedence over If-Modified-Since
  21220. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21221. ASSERT_TRUE(res1->has_header("ETag"));
  21222. std::string etag = res1->get_header_value("ETag");
  21223. Headers h5 = {{"If-None-Match", etag},
  21224. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21225. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21226. ASSERT_TRUE(res5);
  21227. EXPECT_EQ(304, res5->status);
  21228. svr.stop();
  21229. t.join();
  21230. std::remove(fname);
  21231. }
  21232. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21233. using namespace httplib;
  21234. Server svr;
  21235. // Endpoint that returns compressible content
  21236. svr.Get("/compressible", [](const Request &, Response &res) {
  21237. // Return a large enough body to trigger compression
  21238. std::string body(1000, 'a');
  21239. res.set_content(body, "text/plain");
  21240. });
  21241. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21242. svr.wait_until_ready();
  21243. Client cli(HOST, PORT);
  21244. // Request with gzip support: should get Vary header when compressed
  21245. cli.set_compress(true);
  21246. auto res1 = cli.Get("/compressible");
  21247. ASSERT_TRUE(res1);
  21248. EXPECT_EQ(200, res1->status);
  21249. // If Content-Encoding is set, Vary should also be set
  21250. if (res1->has_header("Content-Encoding")) {
  21251. EXPECT_TRUE(res1->has_header("Vary"));
  21252. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21253. }
  21254. // Request without Accept-Encoding header: should not have compression
  21255. Headers h_no_compress;
  21256. auto res2 = cli.Get("/compressible", h_no_compress);
  21257. ASSERT_TRUE(res2);
  21258. EXPECT_EQ(200, res2->status);
  21259. // Verify Vary header is present when compression is applied
  21260. // (the exact behavior depends on server configuration)
  21261. svr.stop();
  21262. t.join();
  21263. }
  21264. TEST(ETagTest, IfRangeWithETag) {
  21265. using namespace httplib;
  21266. // Create a test file with known content
  21267. const char *fname = "if_range_testfile.txt";
  21268. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  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. // First request: get ETag
  21280. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21281. ASSERT_TRUE(res1);
  21282. ASSERT_EQ(200, res1->status);
  21283. ASSERT_TRUE(res1->has_header("ETag"));
  21284. std::string etag = res1->get_header_value("ETag");
  21285. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21286. // Since our server generates weak ETags (W/"..."), If-Range with our
  21287. // ETag should NOT result in partial content - it should return full content.
  21288. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21289. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21290. ASSERT_TRUE(res2);
  21291. // Weak ETag in If-Range -> full content (200), not partial (206)
  21292. EXPECT_EQ(200, res2->status);
  21293. EXPECT_EQ(content, res2->body);
  21294. EXPECT_FALSE(res2->has_header("Content-Range"));
  21295. // Range request with non-matching If-Range (ETag): should get 200 (full
  21296. // content)
  21297. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21298. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21299. ASSERT_TRUE(res3);
  21300. EXPECT_EQ(200, res3->status);
  21301. EXPECT_EQ(content, res3->body);
  21302. EXPECT_FALSE(res3->has_header("Content-Range"));
  21303. // Range request with strong ETag (hypothetical - our server doesn't generate
  21304. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21305. // should return full content)
  21306. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21307. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21308. ASSERT_TRUE(res4);
  21309. EXPECT_EQ(200, res4->status);
  21310. EXPECT_EQ(content, res4->body);
  21311. EXPECT_FALSE(res4->has_header("Content-Range"));
  21312. svr.stop();
  21313. t.join();
  21314. std::remove(fname);
  21315. }
  21316. TEST(ETagTest, IfRangeWithDate) {
  21317. using namespace httplib;
  21318. // Create a test file
  21319. const char *fname = "if_range_date_testfile.txt";
  21320. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21321. {
  21322. std::ofstream ofs(fname);
  21323. ofs << content;
  21324. ASSERT_TRUE(ofs.good());
  21325. }
  21326. Server svr;
  21327. svr.set_mount_point("/static", ".");
  21328. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21329. svr.wait_until_ready();
  21330. Client cli(HOST, PORT);
  21331. // First request: get Last-Modified
  21332. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21333. ASSERT_TRUE(res1);
  21334. ASSERT_EQ(200, res1->status);
  21335. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21336. std::string last_modified = res1->get_header_value("Last-Modified");
  21337. // Range request with matching If-Range (date): should get 206
  21338. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21339. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21340. ASSERT_TRUE(res2);
  21341. EXPECT_EQ(206, res2->status);
  21342. EXPECT_EQ("FGHIJ", res2->body);
  21343. // Range request with old If-Range date: should get 200 (full content)
  21344. Headers h3 = {{"Range", "bytes=5-9"},
  21345. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21346. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21347. ASSERT_TRUE(res3);
  21348. EXPECT_EQ(200, res3->status);
  21349. EXPECT_EQ(content, res3->body);
  21350. // Range request with future If-Range date: should get 206
  21351. Headers h4 = {{"Range", "bytes=0-4"},
  21352. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21353. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21354. ASSERT_TRUE(res4);
  21355. EXPECT_EQ(206, res4->status);
  21356. EXPECT_EQ("ABCDE", res4->body);
  21357. svr.stop();
  21358. t.join();
  21359. std::remove(fname);
  21360. }
  21361. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21362. using namespace httplib;
  21363. const char *fname = "etag_malformed.txt";
  21364. const char *content = "malformed-etag";
  21365. {
  21366. std::ofstream ofs(fname);
  21367. ofs << content;
  21368. ASSERT_TRUE(ofs.good());
  21369. }
  21370. Server svr;
  21371. svr.set_mount_point("/static", ".");
  21372. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21373. svr.wait_until_ready();
  21374. Client cli(HOST, PORT);
  21375. // baseline: should get 200 and an ETag
  21376. auto res1 = cli.Get("/static/etag_malformed.txt");
  21377. ASSERT_TRUE(res1);
  21378. ASSERT_EQ(200, res1->status);
  21379. ASSERT_TRUE(res1->has_header("ETag"));
  21380. // Malformed ETag value (missing quotes) should be treated as non-matching
  21381. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21382. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21383. ASSERT_TRUE(res_bad);
  21384. EXPECT_EQ(200, res_bad->status);
  21385. // Whitespace-only header value should be considered invalid / non-matching
  21386. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21387. "Host: localhost\r\n"
  21388. "If-None-Match: \r\n"
  21389. "Connection: close\r\n"
  21390. "\r\n";
  21391. std::string out;
  21392. ASSERT_TRUE(send_request(5, raw_req, &out));
  21393. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21394. svr.stop();
  21395. t.join();
  21396. std::remove(fname);
  21397. }
  21398. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21399. using namespace httplib;
  21400. const char *fname = "ims_invalid_format.txt";
  21401. const char *content = "ims-bad-format";
  21402. {
  21403. std::ofstream ofs(fname);
  21404. ofs << content;
  21405. ASSERT_TRUE(ofs.good());
  21406. }
  21407. Server svr;
  21408. svr.set_mount_point("/static", ".");
  21409. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21410. svr.wait_until_ready();
  21411. Client cli(HOST, PORT);
  21412. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21413. ASSERT_TRUE(res1);
  21414. ASSERT_EQ(200, res1->status);
  21415. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21416. // If-Modified-Since with invalid format should not result in 304
  21417. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21418. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21419. ASSERT_TRUE(res_bad);
  21420. EXPECT_EQ(200, res_bad->status);
  21421. // If-Range with invalid date format should be treated as mismatch -> full
  21422. // content (200)
  21423. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21424. {"If-Range", "invalid-date"}};
  21425. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21426. ASSERT_TRUE(res_ifrange);
  21427. EXPECT_EQ(200, res_ifrange->status);
  21428. svr.stop();
  21429. t.join();
  21430. std::remove(fname);
  21431. }
  21432. TEST(ETagTest, IfRangeWithMalformedETag) {
  21433. using namespace httplib;
  21434. const char *fname = "ifrange_malformed.txt";
  21435. const std::string content = "0123456789";
  21436. {
  21437. std::ofstream ofs(fname);
  21438. ofs << content;
  21439. ASSERT_TRUE(ofs.good());
  21440. }
  21441. Server svr;
  21442. svr.set_mount_point("/static", ".");
  21443. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21444. svr.wait_until_ready();
  21445. Client cli(HOST, PORT);
  21446. // First request: get ETag
  21447. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21448. ASSERT_TRUE(res1);
  21449. ASSERT_EQ(200, res1->status);
  21450. ASSERT_TRUE(res1->has_header("ETag"));
  21451. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21452. // full content (200)
  21453. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21454. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21455. ASSERT_TRUE(res2);
  21456. EXPECT_EQ(200, res2->status);
  21457. EXPECT_EQ(content, res2->body);
  21458. svr.stop();
  21459. t.join();
  21460. std::remove(fname);
  21461. }
  21462. TEST(ETagTest, ExtremeLargeDateValues) {
  21463. using namespace httplib;
  21464. const char *fname = "ims_extreme_date.txt";
  21465. const char *content = "ims-extreme-date";
  21466. {
  21467. std::ofstream ofs(fname);
  21468. ofs << content;
  21469. ASSERT_TRUE(ofs.good());
  21470. }
  21471. Server svr;
  21472. svr.set_mount_point("/static", ".");
  21473. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21474. svr.wait_until_ready();
  21475. Client cli(HOST, PORT);
  21476. auto res1 = cli.Get(std::string("/static/") + fname);
  21477. ASSERT_TRUE(res1);
  21478. ASSERT_EQ(200, res1->status);
  21479. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21480. // Extremely large year that may overflow date parsing routines.
  21481. Headers h_large_date = {
  21482. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21483. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21484. ASSERT_TRUE(res_bad);
  21485. // Expect server to treat this as invalid/mismatch and return full content
  21486. EXPECT_EQ(200, res_bad->status);
  21487. // If-Range with extremely large date should be treated as mismatch -> full
  21488. // content (200)
  21489. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21490. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21491. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21492. ASSERT_TRUE(res_ifrange);
  21493. EXPECT_EQ(200, res_ifrange->status);
  21494. svr.stop();
  21495. t.join();
  21496. std::remove(fname);
  21497. }
  21498. TEST(ETagTest, NegativeFileModificationTime) {
  21499. using namespace httplib;
  21500. const char *fname = "ims_negative_mtime.txt";
  21501. const std::string content = "negative-mtime";
  21502. {
  21503. std::ofstream ofs(fname);
  21504. ofs << content;
  21505. ASSERT_TRUE(ofs.good());
  21506. }
  21507. // Try to set file mtime to a negative value. This may fail on some
  21508. // platforms/filesystems; if it fails, the test will still verify server
  21509. // behaves safely by performing a regular conditional request.
  21510. #if defined(__APPLE__) || defined(__linux__)
  21511. bool set_negative = false;
  21512. do {
  21513. struct timeval times[2];
  21514. // access time: now
  21515. times[0].tv_sec = time(nullptr);
  21516. times[0].tv_usec = 0;
  21517. // modification time: negative (e.g., -1)
  21518. times[1].tv_sec = -1;
  21519. times[1].tv_usec = 0;
  21520. if (utimes(fname, times) == 0) { set_negative = true; }
  21521. } while (0);
  21522. #else
  21523. bool set_negative = false;
  21524. #endif
  21525. Server svr;
  21526. svr.set_mount_point("/static", ".");
  21527. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21528. svr.wait_until_ready();
  21529. Client cli(HOST, PORT);
  21530. auto res1 = cli.Get(std::string("/static/") + fname);
  21531. ASSERT_TRUE(res1);
  21532. ASSERT_EQ(200, res1->status);
  21533. bool has_last_modified = res1->has_header("Last-Modified");
  21534. std::string last_modified;
  21535. if (has_last_modified) {
  21536. last_modified = res1->get_header_value("Last-Modified");
  21537. }
  21538. if (set_negative) {
  21539. // If we successfully set a negative mtime, ensure server returns a
  21540. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21541. // with an old date and ensure server handles it without crash.
  21542. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21543. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21544. ASSERT_TRUE(res2);
  21545. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21546. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21547. } else {
  21548. // Could not set negative mtime on this platform; fall back to verifying
  21549. // that normal invalid/malformed dates are treated safely (non-304).
  21550. Headers h_bad_date = {
  21551. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21552. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21553. ASSERT_TRUE(res_bad);
  21554. EXPECT_EQ(200, res_bad->status);
  21555. }
  21556. svr.stop();
  21557. t.join();
  21558. std::remove(fname);
  21559. }
  21560. //==============================================================================
  21561. // Integration Tests with Server
  21562. //==============================================================================
  21563. class SSEIntegrationTest : public ::testing::Test {
  21564. protected:
  21565. void SetUp() override {
  21566. stop_server_.store(false);
  21567. events_.clear();
  21568. server_ = httplib::detail::make_unique<Server>();
  21569. setup_server();
  21570. start_server();
  21571. }
  21572. void TearDown() override {
  21573. stop_server_.store(true);
  21574. event_cv_.notify_all();
  21575. server_->stop();
  21576. if (server_thread_.joinable()) { server_thread_.join(); }
  21577. }
  21578. void setup_server() {
  21579. // Simple SSE endpoint
  21580. server_->Get("/events", [this](const Request &req, Response &res) {
  21581. auto last_id = req.get_header_value("Last-Event-ID");
  21582. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21583. res.set_chunked_content_provider(
  21584. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21585. std::unique_lock<std::mutex> lock(event_mutex_);
  21586. if (event_cv_.wait_for(
  21587. lock, std::chrono::milliseconds(200), [this] {
  21588. return !events_.empty() || stop_server_.load();
  21589. })) {
  21590. if (stop_server_.load()) { return false; }
  21591. if (!events_.empty()) {
  21592. std::string event = events_.front();
  21593. events_.erase(events_.begin());
  21594. sink.write(event.data(), event.size());
  21595. return true;
  21596. }
  21597. }
  21598. return !stop_server_.load();
  21599. });
  21600. });
  21601. // Endpoint that returns error
  21602. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21603. res.status = 500;
  21604. res.set_content("Internal Server Error", "text/plain");
  21605. });
  21606. // Endpoint for custom event types
  21607. server_->Get("/custom-events", [](const Request &, Response &res) {
  21608. res.set_chunked_content_provider(
  21609. "text/event-stream", [](size_t offset, DataSink &sink) {
  21610. if (offset == 0) {
  21611. std::string event = "event: update\ndata: updated\n\n"
  21612. "event: delete\ndata: deleted\n\n";
  21613. sink.write(event.data(), event.size());
  21614. }
  21615. return false; // End stream after sending
  21616. });
  21617. });
  21618. }
  21619. void start_server() {
  21620. port_ = server_->bind_to_any_port(HOST);
  21621. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21622. // Wait for server to start
  21623. while (!server_->is_running()) {
  21624. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21625. }
  21626. }
  21627. int get_port() const { return port_; }
  21628. void send_event(const std::string &event) {
  21629. std::lock_guard<std::mutex> lock(event_mutex_);
  21630. events_.push_back(event);
  21631. event_cv_.notify_all();
  21632. }
  21633. std::unique_ptr<Server> server_;
  21634. std::thread server_thread_;
  21635. std::mutex event_mutex_;
  21636. std::condition_variable event_cv_;
  21637. std::vector<std::string> events_;
  21638. std::atomic<bool> stop_server_{false};
  21639. std::string last_received_event_id_;
  21640. int port_ = 0;
  21641. };
  21642. //==============================================================================
  21643. // SSE Parsing Tests
  21644. //==============================================================================
  21645. class SSEParsingTest : public SSEIntegrationTest {
  21646. protected:
  21647. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21648. // A trailing sentinel event tells when the whole stream has been parsed.
  21649. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21650. auto body = stream + "event: end\ndata: end\n\n";
  21651. server_->Get("/parse", [body](const Request &, Response &res) {
  21652. res.set_content(body, "text/event-stream");
  21653. });
  21654. return collect("/parse");
  21655. }
  21656. // Runs SSEClient against path until an "end" event arrives and returns the
  21657. // messages dispatched before it
  21658. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21659. Client client(HOST, get_port());
  21660. sse::SSEClient sse(client, path);
  21661. std::mutex mutex;
  21662. std::condition_variable cv;
  21663. std::vector<sse::SSEMessage> messages;
  21664. auto done = false;
  21665. sse.on_message([&](const sse::SSEMessage &msg) {
  21666. std::lock_guard<std::mutex> lock(mutex);
  21667. // Ignore a replay from a reconnect that races with stop()
  21668. if (!done) { messages.push_back(msg); }
  21669. });
  21670. sse.on_event("end", [&](const sse::SSEMessage &) {
  21671. std::lock_guard<std::mutex> lock(mutex);
  21672. done = true;
  21673. cv.notify_all();
  21674. });
  21675. sse.set_reconnect_interval(100);
  21676. sse.start_async();
  21677. {
  21678. std::unique_lock<std::mutex> lock(mutex);
  21679. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21680. }
  21681. sse.stop();
  21682. EXPECT_TRUE(done);
  21683. return messages;
  21684. }
  21685. };
  21686. TEST_F(SSEParsingTest, SingleLineData) {
  21687. auto msgs = parse("data: hello\n\n");
  21688. ASSERT_EQ(msgs.size(), 1u);
  21689. EXPECT_EQ(msgs[0].data, "hello");
  21690. EXPECT_EQ(msgs[0].event, "message");
  21691. }
  21692. TEST_F(SSEParsingTest, MultiLineData) {
  21693. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21694. ASSERT_EQ(msgs.size(), 1u);
  21695. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21696. }
  21697. TEST_F(SSEParsingTest, CustomEventType) {
  21698. auto msgs = parse("event: update\ndata: payload\n\n");
  21699. ASSERT_EQ(msgs.size(), 1u);
  21700. EXPECT_EQ(msgs[0].event, "update");
  21701. EXPECT_EQ(msgs[0].data, "payload");
  21702. }
  21703. TEST_F(SSEParsingTest, EventIdHandling) {
  21704. auto msgs = parse("id: 12345\ndata: test\n\n");
  21705. ASSERT_EQ(msgs.size(), 1u);
  21706. EXPECT_EQ(msgs[0].id, "12345");
  21707. }
  21708. TEST_F(SSEParsingTest, EmptyEventId) {
  21709. auto msgs = parse("id:\ndata: test\n\n");
  21710. ASSERT_EQ(msgs.size(), 1u);
  21711. EXPECT_EQ(msgs[0].id, "");
  21712. }
  21713. TEST_F(SSEParsingTest, CommentsIgnored) {
  21714. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21715. ASSERT_EQ(msgs.size(), 1u);
  21716. EXPECT_EQ(msgs[0].data, "hello");
  21717. EXPECT_EQ(msgs[0].event, "message");
  21718. }
  21719. TEST_F(SSEParsingTest, ColonInValue) {
  21720. auto msgs = parse("data: hello:world:test\n\n");
  21721. ASSERT_EQ(msgs.size(), 1u);
  21722. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21723. }
  21724. TEST_F(SSEParsingTest, FieldNameOnly) {
  21725. // A line without a colon is a field name with an empty value
  21726. auto msgs = parse("data\n\n");
  21727. ASSERT_EQ(msgs.size(), 1u);
  21728. EXPECT_EQ(msgs[0].data, "");
  21729. }
  21730. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21731. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21732. ASSERT_EQ(msgs.size(), 1u);
  21733. EXPECT_EQ(msgs[0].event, "update");
  21734. EXPECT_EQ(msgs[0].data, "hello");
  21735. }
  21736. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21737. auto msgs = parse("data\r\n\r\n");
  21738. ASSERT_EQ(msgs.size(), 1u);
  21739. EXPECT_EQ(msgs[0].data, "");
  21740. }
  21741. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21742. auto msgs = parse("event: update\rdata: hello\r\r");
  21743. ASSERT_EQ(msgs.size(), 1u);
  21744. EXPECT_EQ(msgs[0].event, "update");
  21745. EXPECT_EQ(msgs[0].data, "hello");
  21746. }
  21747. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21748. // Chunk boundaries fall inside every \r\n and right before the first one
  21749. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21750. "\n\r", "\nevent: end\ndata: end\n\n"};
  21751. server_->Get("/split", [chunks](const Request &, Response &res) {
  21752. auto i = std::make_shared<size_t>(0);
  21753. res.set_chunked_content_provider(
  21754. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21755. if (*i == chunks.size()) {
  21756. sink.done();
  21757. } else {
  21758. sink.write(chunks[*i].data(), chunks[*i].size());
  21759. (*i)++;
  21760. }
  21761. return true;
  21762. });
  21763. });
  21764. auto msgs = collect("/split");
  21765. ASSERT_EQ(msgs.size(), 1u);
  21766. EXPECT_EQ(msgs[0].event, "update");
  21767. EXPECT_EQ(msgs[0].data, "hello");
  21768. }
  21769. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21770. // Only a BOM at the start of the stream is ignored
  21771. auto msgs = parse("\xEF\xBB\xBF"
  21772. "data: first\n\n"
  21773. "\xEF\xBB\xBF"
  21774. "data: second\n\n");
  21775. ASSERT_EQ(msgs.size(), 1u);
  21776. EXPECT_EQ(msgs[0].data, "first");
  21777. }
  21778. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21779. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21780. ASSERT_EQ(msgs.size(), 1u);
  21781. EXPECT_EQ(msgs[0].data, "hello");
  21782. EXPECT_EQ(msgs[0].event, "message");
  21783. }
  21784. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21785. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21786. ASSERT_EQ(msgs.size(), 2u);
  21787. EXPECT_EQ(msgs[0].data, "hello");
  21788. EXPECT_EQ(msgs[1].data, "hello");
  21789. }
  21790. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21791. // An event without data is not dispatched, and its type must not leak
  21792. // into the next event
  21793. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21794. ASSERT_EQ(msgs.size(), 1u);
  21795. EXPECT_EQ(msgs[0].event, "message");
  21796. EXPECT_EQ(msgs[0].data, "hello");
  21797. }
  21798. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21799. // Also when the empty field replaces an earlier type
  21800. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21801. ASSERT_EQ(msgs.size(), 2u);
  21802. EXPECT_EQ(msgs[0].event, "message");
  21803. EXPECT_EQ(msgs[1].event, "message");
  21804. }
  21805. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21806. // The first connection sends only an id; the second echoes back the
  21807. // Last-Event-ID it was reconnected with
  21808. std::atomic<int> connection_count{0};
  21809. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21810. if (connection_count++ == 0) {
  21811. res.set_content("id: 42\n\n", "text/event-stream");
  21812. } else {
  21813. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21814. "\n\nevent: end\ndata: end\n\n",
  21815. "text/event-stream");
  21816. }
  21817. });
  21818. auto msgs = collect("/id-only");
  21819. ASSERT_EQ(msgs.size(), 1u);
  21820. EXPECT_EQ(msgs[0].data, "42");
  21821. }
  21822. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21823. // The first connection sets an id and then clears it with an empty one; the
  21824. // second reports whether it was reconnected with a Last-Event-ID
  21825. std::atomic<int> connection_count{0};
  21826. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21827. if (connection_count++ == 0) {
  21828. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21829. "text/event-stream");
  21830. } else {
  21831. res.set_content(
  21832. std::string("data: ") +
  21833. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21834. "\n\nevent: end\ndata: end\n\n",
  21835. "text/event-stream");
  21836. }
  21837. });
  21838. auto msgs = collect("/id-clear");
  21839. ASSERT_EQ(msgs.size(), 3u);
  21840. EXPECT_EQ(msgs[0].id, "1");
  21841. EXPECT_EQ(msgs[1].id, "");
  21842. EXPECT_EQ(msgs[2].data, "not sent");
  21843. }
  21844. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21845. // The first connection sets an id and then sends ids that cannot be carried
  21846. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21847. // with
  21848. std::atomic<int> connection_count{0};
  21849. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21850. if (connection_count++ == 0) {
  21851. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21852. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21853. "text/event-stream");
  21854. } else {
  21855. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21856. "\n\nevent: end\ndata: end\n\n",
  21857. "text/event-stream");
  21858. }
  21859. });
  21860. auto msgs = collect("/id-unsendable");
  21861. ASSERT_EQ(msgs.size(), 1u);
  21862. EXPECT_EQ(msgs[0].data, "42");
  21863. }
  21864. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21865. auto msgs = parse("event: notification\nid: evt-42\n"
  21866. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21867. ASSERT_EQ(msgs.size(), 1u);
  21868. EXPECT_EQ(msgs[0].event, "notification");
  21869. EXPECT_EQ(msgs[0].id, "evt-42");
  21870. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21871. }
  21872. TEST(SSEMessageTest, Clear) {
  21873. sse::SSEMessage msg;
  21874. msg.event = "custom";
  21875. msg.data = "some data";
  21876. msg.id = "123";
  21877. msg.clear();
  21878. EXPECT_EQ(msg.event, "message");
  21879. EXPECT_EQ(msg.data, "");
  21880. EXPECT_EQ(msg.id, "");
  21881. }
  21882. //==============================================================================
  21883. // SSE Integration Tests
  21884. //==============================================================================
  21885. // Test: Successful connection and on_open callback
  21886. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21887. // Add a simple endpoint that sends one event and closes
  21888. server_->Get("/simple-event", [](const Request &, Response &res) {
  21889. res.set_chunked_content_provider(
  21890. "text/event-stream", [](size_t offset, DataSink &sink) {
  21891. if (offset == 0) {
  21892. std::string event = "data: hello\n\n";
  21893. sink.write(event.data(), event.size());
  21894. }
  21895. return false; // Close stream after sending
  21896. });
  21897. });
  21898. Client client("localhost", get_port());
  21899. sse::SSEClient sse(client, "/simple-event");
  21900. std::atomic<bool> open_called{false};
  21901. std::atomic<bool> message_received{false};
  21902. sse.on_open([&open_called]() { open_called.store(true); });
  21903. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21904. if (msg.data == "hello") { message_received.store(true); }
  21905. });
  21906. sse.set_reconnect_interval(100);
  21907. sse.set_max_reconnect_attempts(1);
  21908. // Start async
  21909. sse.start_async();
  21910. // Wait for message to be processed
  21911. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21912. sse.stop();
  21913. EXPECT_TRUE(open_called.load());
  21914. EXPECT_TRUE(message_received.load());
  21915. }
  21916. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21917. // A data line that never ends.
  21918. server_->Get("/endless-line", [](const Request &, Response &res) {
  21919. res.set_chunked_content_provider(
  21920. "text/event-stream", [](size_t offset, DataSink &sink) {
  21921. if (offset == 0) { sink.write("data: ", 6); }
  21922. std::string chunk(64 * 1024, 'A');
  21923. return sink.write(chunk.data(), chunk.size());
  21924. });
  21925. });
  21926. Client client("localhost", get_port());
  21927. sse::SSEClient sse(client, "/endless-line");
  21928. std::atomic<bool> too_long{false};
  21929. sse.on_error([&](Error err) {
  21930. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21931. });
  21932. sse.set_max_reconnect_attempts(1);
  21933. sse.start_async();
  21934. for (int i = 0; i < 500 && !too_long; i++) {
  21935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21936. }
  21937. sse.stop();
  21938. EXPECT_TRUE(too_long);
  21939. }
  21940. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21941. // Far more in all than the client's payload limit below.
  21942. server_->Get("/many-events", [](const Request &, Response &res) {
  21943. res.set_chunked_content_provider(
  21944. "text/event-stream", [](size_t offset, DataSink &sink) {
  21945. if (offset == 0) {
  21946. std::string events;
  21947. for (int i = 0; i < 1000; i++) {
  21948. events += "data: message\n\n";
  21949. }
  21950. sink.write(events.data(), events.size());
  21951. }
  21952. return false;
  21953. });
  21954. });
  21955. Client client("localhost", get_port());
  21956. client.set_payload_max_length(1024);
  21957. sse::SSEClient sse(client, "/many-events");
  21958. std::atomic<int> messages{0};
  21959. std::atomic<bool> too_large{false};
  21960. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21961. sse.on_error([&](Error err) {
  21962. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21963. });
  21964. sse.set_max_reconnect_attempts(1);
  21965. sse.start_async();
  21966. for (int i = 0; i < 500 && messages < 1000; i++) {
  21967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21968. }
  21969. sse.stop();
  21970. EXPECT_GE(messages.load(), 1000);
  21971. EXPECT_FALSE(too_large);
  21972. }
  21973. // Test: on_message callback
  21974. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21975. // Endpoint that sends multiple events then closes
  21976. server_->Get("/multi-event", [](const Request &, Response &res) {
  21977. res.set_chunked_content_provider(
  21978. "text/event-stream", [](size_t offset, DataSink &sink) {
  21979. if (offset == 0) {
  21980. std::string events = "data: message1\n\ndata: message2\n\n";
  21981. sink.write(events.data(), events.size());
  21982. }
  21983. return false;
  21984. });
  21985. });
  21986. Client client("localhost", get_port());
  21987. sse::SSEClient sse(client, "/multi-event");
  21988. std::vector<std::string> received_messages;
  21989. std::mutex messages_mutex;
  21990. sse.on_message([&](const sse::SSEMessage &msg) {
  21991. std::lock_guard<std::mutex> lock(messages_mutex);
  21992. received_messages.push_back(msg.data);
  21993. });
  21994. sse.set_reconnect_interval(100);
  21995. sse.set_max_reconnect_attempts(1);
  21996. sse.start_async();
  21997. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21998. sse.stop();
  21999. std::lock_guard<std::mutex> lock(messages_mutex);
  22000. EXPECT_GE(received_messages.size(), 2u);
  22001. if (received_messages.size() >= 2) {
  22002. EXPECT_EQ(received_messages[0], "message1");
  22003. EXPECT_EQ(received_messages[1], "message2");
  22004. }
  22005. }
  22006. // Test: on_event for specific types
  22007. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22008. Client client("localhost", get_port());
  22009. sse::SSEClient sse(client, "/custom-events");
  22010. std::atomic<bool> update_received{false};
  22011. std::atomic<bool> delete_received{false};
  22012. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22013. if (msg.data == "updated") { update_received.store(true); }
  22014. });
  22015. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22016. if (msg.data == "deleted") { delete_received.store(true); }
  22017. });
  22018. sse.set_max_reconnect_attempts(1);
  22019. sse.start_async();
  22020. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22021. sse.stop();
  22022. EXPECT_TRUE(update_received.load());
  22023. EXPECT_TRUE(delete_received.load());
  22024. }
  22025. // Test: on_error callback on connection failure
  22026. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22027. // Connect to a non-existent port
  22028. Client client("localhost", 59999);
  22029. sse::SSEClient sse(client, "/events");
  22030. std::atomic<bool> error_called{false};
  22031. Error received_error = Error::Success;
  22032. sse.on_error([&](Error err) {
  22033. error_called.store(true);
  22034. received_error = err;
  22035. });
  22036. sse.set_reconnect_interval(50);
  22037. sse.set_max_reconnect_attempts(1);
  22038. sse.start_async();
  22039. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22040. sse.stop();
  22041. EXPECT_TRUE(error_called.load());
  22042. EXPECT_NE(received_error, Error::Success);
  22043. }
  22044. // Test: Last-Event-ID header sent on reconnect
  22045. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22046. // Endpoint that sends event with ID
  22047. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22048. res.set_chunked_content_provider(
  22049. "text/event-stream", [](size_t offset, DataSink &sink) {
  22050. if (offset == 0) {
  22051. std::string event = "id: evt-123\ndata: test\n\n";
  22052. sink.write(event.data(), event.size());
  22053. }
  22054. return false;
  22055. });
  22056. });
  22057. Client client("localhost", get_port());
  22058. sse::SSEClient sse(client, "/event-with-id");
  22059. std::atomic<bool> id_received{false};
  22060. sse.on_message([&](const sse::SSEMessage &msg) {
  22061. if (!msg.id.empty()) { id_received.store(true); }
  22062. });
  22063. sse.set_reconnect_interval(100);
  22064. sse.set_max_reconnect_attempts(1);
  22065. sse.start_async();
  22066. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22067. sse.stop();
  22068. EXPECT_TRUE(id_received.load());
  22069. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22070. }
  22071. // Test: Manual stop
  22072. TEST_F(SSEIntegrationTest, ManualStop) {
  22073. // Endpoint that sends one event and stays open briefly. The server outlives
  22074. // this test body, so the provider uses the fixture's flag, not a local.
  22075. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22076. res.set_chunked_content_provider(
  22077. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22078. if (offset == 0) {
  22079. std::string event = "data: connected\n\n";
  22080. sink.write(event.data(), event.size());
  22081. }
  22082. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22083. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22084. }
  22085. return false;
  22086. });
  22087. });
  22088. Client client("localhost", get_port());
  22089. sse::SSEClient sse(client, "/stay-open");
  22090. std::atomic<bool> connected{false};
  22091. sse.on_open([&connected]() { connected.store(true); });
  22092. sse.set_reconnect_interval(100);
  22093. sse.set_max_reconnect_attempts(1);
  22094. sse.start_async();
  22095. // Wait for connection to establish
  22096. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22097. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22098. }
  22099. EXPECT_TRUE(connected.load());
  22100. EXPECT_TRUE(sse.is_connected());
  22101. // Signal handler to stop
  22102. stop_server_.store(true);
  22103. // Stop SSE client
  22104. sse.stop();
  22105. EXPECT_FALSE(sse.is_connected());
  22106. }
  22107. // Sends one event, then nothing until stop is set
  22108. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22109. return [&stop](const Request &, Response &res) {
  22110. res.set_chunked_content_provider(
  22111. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22112. if (offset == 0) {
  22113. std::string event = "data: hello\n\n";
  22114. sink.write(event.data(), event.size());
  22115. }
  22116. while (!stop.load()) {
  22117. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22118. }
  22119. return false;
  22120. });
  22121. };
  22122. }
  22123. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22124. static void check_stop_interrupts_blocked_read(Client &client) {
  22125. client.set_read_timeout(30, 0);
  22126. for (auto by_destructor : {false, true}) {
  22127. std::atomic<bool> received{false};
  22128. std::chrono::steady_clock::time_point start;
  22129. {
  22130. sse::SSEClient sse(client, "/idle-stream");
  22131. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22132. sse.start_async();
  22133. for (int i = 0; i < 500 && !received.load(); ++i) {
  22134. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22135. }
  22136. ASSERT_TRUE(received.load());
  22137. // Let the client block in the next read
  22138. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22139. start = std::chrono::steady_clock::now();
  22140. if (!by_destructor) { sse.stop(); }
  22141. }
  22142. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22143. std::chrono::seconds(2));
  22144. }
  22145. }
  22146. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22147. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22148. Client client("localhost", get_port());
  22149. check_stop_interrupts_blocked_read(client);
  22150. }
  22151. #ifdef CPPHTTPLIB_SSL_ENABLED
  22152. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22154. std::atomic<bool> done{false};
  22155. svr.Get("/idle-stream", idle_event_stream(done));
  22156. auto port = svr.bind_to_any_port(HOST);
  22157. std::thread t([&] { svr.listen_after_bind(); });
  22158. auto se = detail::scope_exit([&] {
  22159. done.store(true);
  22160. svr.stop();
  22161. t.join();
  22162. });
  22163. svr.wait_until_ready();
  22164. Client client("https://localhost:" + std::to_string(port));
  22165. client.enable_server_certificate_verification(false);
  22166. check_stop_interrupts_blocked_read(client);
  22167. }
  22168. #endif
  22169. // Test: SSEClient with custom headers
  22170. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22171. // Setup a server endpoint that checks for custom header
  22172. std::atomic<bool> header_received{false};
  22173. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22174. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22175. header_received.store(true);
  22176. }
  22177. res.set_chunked_content_provider("text/event-stream",
  22178. [](size_t, DataSink &) { return false; });
  22179. });
  22180. Client client("localhost", get_port());
  22181. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22182. sse::SSEClient sse(client, "/header-check", headers);
  22183. sse.set_max_reconnect_attempts(1);
  22184. sse.start_async();
  22185. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22186. sse.stop();
  22187. EXPECT_TRUE(header_received.load());
  22188. }
  22189. // Test: Reconnect interval configuration
  22190. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22191. Client client("localhost", get_port());
  22192. sse::SSEClient sse(client, "/events");
  22193. auto &result = sse.set_reconnect_interval(500);
  22194. // Builder pattern should return reference to self
  22195. EXPECT_EQ(&result, &sse);
  22196. }
  22197. // Test: Max reconnect attempts
  22198. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22199. // Connect to non-existent port to force reconnects
  22200. Client client("localhost", 59998);
  22201. sse::SSEClient sse(client, "/events");
  22202. std::atomic<int> error_count{0};
  22203. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22204. sse.set_reconnect_interval(50);
  22205. sse.set_max_reconnect_attempts(2);
  22206. auto start = std::chrono::steady_clock::now();
  22207. sse.start(); // Blocking call
  22208. auto end = std::chrono::steady_clock::now();
  22209. // Should have stopped after 2 failed attempts
  22210. EXPECT_GE(error_count.load(), 2);
  22211. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22212. auto duration =
  22213. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22214. #ifdef _WIN32
  22215. // Windows is much slower for socket connection failures
  22216. EXPECT_LT(duration.count(), 7000);
  22217. #else
  22218. EXPECT_LT(duration.count(), 1000);
  22219. #endif
  22220. }
  22221. // Test: Multi-line data in integration
  22222. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22223. // Endpoint with multi-line data
  22224. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22225. res.set_chunked_content_provider(
  22226. "text/event-stream", [](size_t offset, DataSink &sink) {
  22227. if (offset == 0) {
  22228. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22229. sink.write(event.data(), event.size());
  22230. }
  22231. return false;
  22232. });
  22233. });
  22234. Client client("localhost", get_port());
  22235. sse::SSEClient sse(client, "/multiline-data");
  22236. std::string received_data;
  22237. std::mutex data_mutex;
  22238. sse.on_message([&](const sse::SSEMessage &msg) {
  22239. std::lock_guard<std::mutex> lock(data_mutex);
  22240. received_data = msg.data;
  22241. });
  22242. sse.set_reconnect_interval(100);
  22243. sse.set_max_reconnect_attempts(1);
  22244. sse.start_async();
  22245. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22246. sse.stop();
  22247. std::lock_guard<std::mutex> lock(data_mutex);
  22248. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22249. }
  22250. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22251. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22252. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22253. DataSink &sink) {
  22254. if (offset == 0) {
  22255. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22256. sink.write(events.data(), events.size());
  22257. }
  22258. return false;
  22259. });
  22260. });
  22261. Client client("localhost", get_port());
  22262. sse::SSEClient sse(client, "/empty-data-lines");
  22263. std::mutex mutex;
  22264. std::condition_variable cv;
  22265. std::vector<std::string> received;
  22266. sse.on_message([&](const sse::SSEMessage &msg) {
  22267. std::lock_guard<std::mutex> lock(mutex);
  22268. received.push_back(msg.data);
  22269. cv.notify_all();
  22270. });
  22271. sse.set_max_reconnect_attempts(1);
  22272. sse.start_async();
  22273. {
  22274. std::unique_lock<std::mutex> lock(mutex);
  22275. cv.wait_for(lock, std::chrono::seconds(2),
  22276. [&] { return received.size() >= 3; });
  22277. }
  22278. sse.stop();
  22279. ASSERT_GE(received.size(), 3u);
  22280. EXPECT_EQ(received[0], "");
  22281. EXPECT_EQ(received[1], "\nhello");
  22282. EXPECT_EQ(received[2], "");
  22283. }
  22284. // Test: Auto-reconnect after server disconnection
  22285. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22286. std::atomic<int> connection_count{0};
  22287. std::atomic<int> message_count{0};
  22288. // Endpoint that sends one event and closes, forcing reconnect
  22289. server_->Get("/reconnect-test",
  22290. [&connection_count](const Request &, Response &res) {
  22291. connection_count.fetch_add(1);
  22292. res.set_chunked_content_provider(
  22293. "text/event-stream", [](size_t offset, DataSink &sink) {
  22294. if (offset == 0) {
  22295. std::string event = "data: hello\n\n";
  22296. sink.write(event.data(), event.size());
  22297. }
  22298. return false; // Close connection after sending
  22299. });
  22300. });
  22301. Client client("localhost", get_port());
  22302. sse::SSEClient sse(client, "/reconnect-test");
  22303. sse.on_message([&message_count](const sse::SSEMessage &) {
  22304. message_count.fetch_add(1);
  22305. });
  22306. sse.set_reconnect_interval(100);
  22307. sse.set_max_reconnect_attempts(3);
  22308. sse.start_async();
  22309. // Wait long enough for multiple reconnects
  22310. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22311. sse.stop();
  22312. // Should have connected multiple times (initial + reconnects)
  22313. EXPECT_GE(connection_count.load(), 2);
  22314. // Should have received messages from multiple connections
  22315. EXPECT_GE(message_count.load(), 2);
  22316. }
  22317. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22318. std::atomic<int> connection_count{0};
  22319. // Neither Content-Length nor chunked: the close ends the stream
  22320. server_->Get("/close-delimited",
  22321. [&connection_count](const Request &, Response &res) {
  22322. connection_count.fetch_add(1);
  22323. res.set_content_provider(
  22324. "text/event-stream", [](size_t offset, DataSink &sink) {
  22325. if (offset == 0) {
  22326. std::string event = "data: hello\n\n";
  22327. sink.write(event.data(), event.size());
  22328. } else {
  22329. sink.done();
  22330. }
  22331. return true;
  22332. });
  22333. });
  22334. Client client("localhost", get_port());
  22335. sse::SSEClient sse(client, "/close-delimited");
  22336. std::atomic<int> error_count{0};
  22337. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22338. sse.set_reconnect_interval(100);
  22339. sse.start_async();
  22340. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22341. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22342. }
  22343. sse.stop();
  22344. // Reconnects as after any end of the stream, but reports no error
  22345. EXPECT_GE(connection_count.load(), 2);
  22346. EXPECT_EQ(0, error_count.load());
  22347. }
  22348. // Test: A retry field that is not all ASCII digits is ignored
  22349. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22350. std::atomic<int> connection_count{0};
  22351. server_->Get("/bad-retry",
  22352. [&connection_count](const Request &, Response &res) {
  22353. connection_count.fetch_add(1);
  22354. res.set_chunked_content_provider(
  22355. "text/event-stream", [](size_t offset, DataSink &sink) {
  22356. if (offset == 0) {
  22357. std::string event = "retry: -1\ndata: hello\n\n";
  22358. sink.write(event.data(), event.size());
  22359. }
  22360. return false;
  22361. });
  22362. });
  22363. Client client("localhost", get_port());
  22364. sse::SSEClient sse(client, "/bad-retry");
  22365. sse.set_reconnect_interval(10000);
  22366. sse.start_async();
  22367. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22368. sse.stop();
  22369. EXPECT_EQ(connection_count.load(), 1);
  22370. }
  22371. // Test: A retry field of all ASCII digits sets the reconnection time
  22372. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22373. std::mutex mutex;
  22374. std::condition_variable cv;
  22375. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22376. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22377. {
  22378. std::lock_guard<std::mutex> lock(mutex);
  22379. connected_at.push_back(std::chrono::steady_clock::now());
  22380. cv.notify_all();
  22381. }
  22382. res.set_chunked_content_provider(
  22383. "text/event-stream", [](size_t offset, DataSink &sink) {
  22384. if (offset == 0) {
  22385. std::string event = "retry: 0\ndata: hello\n\n";
  22386. sink.write(event.data(), event.size());
  22387. }
  22388. return false;
  22389. });
  22390. });
  22391. Client client("localhost", get_port());
  22392. sse::SSEClient sse(client, "/zero-retry");
  22393. sse.set_reconnect_interval(10000);
  22394. sse.start_async();
  22395. {
  22396. std::unique_lock<std::mutex> lock(mutex);
  22397. cv.wait_for(lock, std::chrono::seconds(5),
  22398. [&] { return connected_at.size() >= 2; });
  22399. }
  22400. sse.stop();
  22401. // The server-supplied interval is applied, but never below 100ms, so
  22402. // "retry: 0" does not cause a busy reconnect loop
  22403. std::lock_guard<std::mutex> lock(mutex);
  22404. ASSERT_GE(connected_at.size(), 2u);
  22405. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22406. connected_at[1] - connected_at[0])
  22407. .count();
  22408. EXPECT_GE(interval_ms, 100);
  22409. }
  22410. // Test: Last-Event-ID sent on reconnect
  22411. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22412. std::atomic<int> connection_count{0};
  22413. std::vector<std::string> received_last_event_ids;
  22414. std::mutex id_mutex;
  22415. // Endpoint that checks Last-Event-ID header and sends event with ID
  22416. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22417. int conn = connection_count.fetch_add(1);
  22418. // Capture the Last-Event-ID header from each connection
  22419. {
  22420. std::lock_guard<std::mutex> lock(id_mutex);
  22421. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22422. }
  22423. res.set_chunked_content_provider(
  22424. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22425. if (offset == 0) {
  22426. std::string event =
  22427. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22428. sink.write(event.data(), event.size());
  22429. }
  22430. return false;
  22431. });
  22432. });
  22433. Client client("localhost", get_port());
  22434. sse::SSEClient sse(client, "/reconnect-with-id");
  22435. sse.set_reconnect_interval(100);
  22436. sse.set_max_reconnect_attempts(3);
  22437. sse.start_async();
  22438. // Wait for at least 2 connections
  22439. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22440. sse.stop();
  22441. // Verify behavior
  22442. std::lock_guard<std::mutex> lock(id_mutex);
  22443. EXPECT_GE(received_last_event_ids.size(), 2u);
  22444. // First connection should have no Last-Event-ID
  22445. if (!received_last_event_ids.empty()) {
  22446. EXPECT_EQ(received_last_event_ids[0], "");
  22447. }
  22448. // Second connection should have Last-Event-ID from first connection
  22449. if (received_last_event_ids.size() >= 2) {
  22450. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22451. }
  22452. }
  22453. // Test: set_headers updates headers used on reconnect
  22454. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22455. std::vector<std::string> received_tokens;
  22456. std::mutex token_mutex;
  22457. // Endpoint that captures Authorization header
  22458. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22459. {
  22460. std::lock_guard<std::mutex> lock(token_mutex);
  22461. received_tokens.push_back(req.get_header_value("Authorization"));
  22462. }
  22463. res.set_chunked_content_provider(
  22464. "text/event-stream", [](size_t offset, DataSink &sink) {
  22465. if (offset == 0) {
  22466. std::string event = "data: hello\n\n";
  22467. sink.write(event.data(), event.size());
  22468. }
  22469. return false; // Close connection to trigger reconnect
  22470. });
  22471. });
  22472. Client client("localhost", get_port());
  22473. Headers headers = {{"Authorization", "Bearer old-token"}};
  22474. sse::SSEClient sse(client, "/auth-check", headers);
  22475. // Update headers on each successful connection
  22476. sse.on_open(
  22477. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22478. sse.set_reconnect_interval(100);
  22479. sse.set_max_reconnect_attempts(3);
  22480. sse.start_async();
  22481. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22482. sse.stop();
  22483. std::lock_guard<std::mutex> lock(token_mutex);
  22484. ASSERT_GE(received_tokens.size(), 2u);
  22485. // First connection uses original header
  22486. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22487. // Second connection uses updated header from set_headers
  22488. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22489. }
  22490. // Test: 401 allows reconnection (so on_error can refresh headers)
  22491. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22492. std::atomic<int> connection_count{0};
  22493. // Endpoint: returns 401 on first attempt, 200 on second
  22494. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22495. int conn = connection_count.fetch_add(1);
  22496. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22497. res.status = StatusCode::Unauthorized_401;
  22498. res.set_content("Unauthorized", "text/plain");
  22499. return;
  22500. }
  22501. res.set_chunked_content_provider(
  22502. "text/event-stream", [](size_t offset, DataSink &sink) {
  22503. if (offset == 0) {
  22504. std::string event = "data: authenticated\n\n";
  22505. sink.write(event.data(), event.size());
  22506. }
  22507. return false;
  22508. });
  22509. });
  22510. Client client("localhost", get_port());
  22511. Headers headers = {{"Authorization", "Bearer expired"}};
  22512. sse::SSEClient sse(client, "/auth-retry", headers);
  22513. std::atomic<bool> message_received{false};
  22514. // Refresh token on error
  22515. sse.on_error(
  22516. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22517. sse.on_message([&](const sse::SSEMessage &msg) {
  22518. if (msg.data == "authenticated") { message_received.store(true); }
  22519. });
  22520. sse.set_reconnect_interval(100);
  22521. sse.set_max_reconnect_attempts(3);
  22522. sse.start_async();
  22523. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22524. sse.stop();
  22525. // Should have reconnected after 401 and succeeded with new token
  22526. EXPECT_GE(connection_count.load(), 2);
  22527. EXPECT_TRUE(message_received.load());
  22528. }
  22529. TEST(Issue2318Test, EmptyHostString) {
  22530. {
  22531. httplib::Client cli_empty("", PORT);
  22532. auto res = cli_empty.Get("/");
  22533. ASSERT_FALSE(res);
  22534. EXPECT_EQ(httplib::Error::Connection, res.error());
  22535. }
  22536. {
  22537. httplib::Client cli(" ", PORT);
  22538. auto res = cli.Get("/");
  22539. ASSERT_FALSE(res);
  22540. EXPECT_EQ(httplib::Error::Connection, res.error());
  22541. }
  22542. }
  22543. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22544. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22545. Server svr;
  22546. // Set a small payload limit (1KB)
  22547. svr.set_payload_max_length(1024);
  22548. svr.Post("/test", [&](const Request &req, Response &res) {
  22549. res.set_content("Body size: " + std::to_string(req.body.size()),
  22550. "text/plain");
  22551. });
  22552. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22553. auto se = detail::scope_exit([&] {
  22554. svr.stop();
  22555. listen_thread.join();
  22556. });
  22557. svr.wait_until_ready();
  22558. // Create data that compresses well but exceeds limit when decompressed
  22559. // 8KB of repeated null bytes compresses to a very small size
  22560. std::string original_data(8 * 1024, '\0');
  22561. // Compress the data using gzip
  22562. std::string compressed_data;
  22563. detail::gzip_compressor compressor;
  22564. compressor.compress(original_data.data(), original_data.size(), true,
  22565. [&](const char *data, size_t size) {
  22566. compressed_data.append(data, size);
  22567. return true;
  22568. });
  22569. // Verify compression worked (compressed should be much smaller)
  22570. ASSERT_LT(compressed_data.size(), original_data.size());
  22571. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22572. // Send compressed data with Content-Encoding: gzip
  22573. Client cli(HOST, PORT);
  22574. Headers headers = {{"Content-Encoding", "gzip"}};
  22575. auto res =
  22576. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22577. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22579. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22580. }
  22581. #endif
  22582. // ============================================================================
  22583. // OpenSSL-Specific Tests
  22584. // ============================================================================
  22585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22586. X509 *readCertificate(const std::string &strFileName) {
  22587. std::ifstream inStream(strFileName);
  22588. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22589. std::istreambuf_iterator<char>());
  22590. if (strCertPEM.empty()) return (nullptr);
  22591. BIO *pbCert = BIO_new(BIO_s_mem());
  22592. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22593. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22594. BIO_free(pbCert);
  22595. return (pCert);
  22596. }
  22597. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22598. std::ifstream inStream(strFileName);
  22599. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22600. std::istreambuf_iterator<char>());
  22601. if (strPrivateKeyPEM.empty()) return (nullptr);
  22602. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22603. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22604. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22605. BIO_free(pbPrivKey);
  22606. return (pPrivateKey);
  22607. }
  22608. TEST(BindServerTest, UpdateCerts) {
  22609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22610. int port = svr.bind_to_any_port("0.0.0.0");
  22611. ASSERT_TRUE(svr.is_valid());
  22612. ASSERT_TRUE(port > 0);
  22613. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22614. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22615. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22616. ASSERT_TRUE(cert != nullptr);
  22617. ASSERT_TRUE(ca_cert != nullptr);
  22618. ASSERT_TRUE(key != nullptr);
  22619. X509_STORE *cert_store = X509_STORE_new();
  22620. X509_STORE_add_cert(cert_store, ca_cert);
  22621. // svr.update_certs(cert, key, cert_store); // deprecated
  22622. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22623. CLIENT_CA_CERT_FILE);
  22624. ASSERT_TRUE(svr.is_valid());
  22625. svr.stop();
  22626. X509_STORE_free(cert_store);
  22627. X509_free(cert);
  22628. X509_free(ca_cert);
  22629. EVP_PKEY_free(key);
  22630. }
  22631. // Test that update_certs() updates client CA list correctly
  22632. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22633. // Start with file-based constructor
  22634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22635. ASSERT_TRUE(svr.is_valid());
  22636. // Initially no client CA list should be set
  22637. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22638. ASSERT_TRUE(ssl_ctx != nullptr);
  22639. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22640. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22641. // Now update with client CA (PEM string)
  22642. std::string cert_pem, key_pem, ca_pem;
  22643. read_file(SERVER_CERT_FILE, cert_pem);
  22644. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22645. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22646. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22647. ASSERT_TRUE(svr.is_valid());
  22648. // Now client CA list should be set
  22649. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22650. ASSERT_TRUE(ca_list_after != nullptr);
  22651. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22652. }
  22653. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22654. // Test that the file-path SSLServer constructor properly sets the client CA
  22655. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22657. ASSERT_TRUE(svr.is_valid());
  22658. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22659. ASSERT_TRUE(ssl_ctx != nullptr);
  22660. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22661. ASSERT_TRUE(ca_list != nullptr);
  22662. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22663. }
  22664. #endif
  22665. // ============================================================================
  22666. // MbedTLS-Specific Tests
  22667. // ============================================================================
  22668. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22669. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22670. using namespace httplib::tls;
  22671. // Track if callback was invoked
  22672. bool callback_invoked = false;
  22673. // The callback receives void* ctx which is actually MbedTlsContext*
  22674. // We can access the mbedtls_ssl_config via the context
  22675. auto setup_callback = [&callback_invoked](void *ctx) {
  22676. callback_invoked = true;
  22677. // Cast to MbedTlsContext* to access the ssl config
  22678. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22679. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22680. // Use static variables to hold certificate data (simplified for test)
  22681. static mbedtls_x509_crt own_cert;
  22682. static mbedtls_pk_context own_key;
  22683. static mbedtls_x509_crt ca_chain;
  22684. static bool initialized = false;
  22685. if (!initialized) {
  22686. mbedtls_x509_crt_init(&own_cert);
  22687. mbedtls_pk_init(&own_key);
  22688. mbedtls_x509_crt_init(&ca_chain);
  22689. // Load server certificate
  22690. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22691. return false;
  22692. }
  22693. // Load server private key.
  22694. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22695. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22696. #if MBEDTLS_VERSION_MAJOR == 3
  22697. ,
  22698. mbedtls_ctr_drbg_random, nullptr
  22699. #endif
  22700. ) != 0) {
  22701. return false;
  22702. }
  22703. // Load CA chain for client verification
  22704. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22705. return false;
  22706. }
  22707. initialized = true;
  22708. }
  22709. // Configure the SSL config
  22710. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22711. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22712. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22713. // Set minimum TLS version using mbedTLS native API
  22714. #if MBEDTLS_VERSION_MAJOR >= 3
  22715. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22716. #else
  22717. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22718. MBEDTLS_SSL_MINOR_VERSION_3);
  22719. #endif
  22720. return true;
  22721. };
  22722. SSLServer svr(setup_callback);
  22723. ASSERT_TRUE(svr.is_valid());
  22724. ASSERT_TRUE(callback_invoked);
  22725. svr.Get("/test", [&](const Request &req, Response &res) {
  22726. res.set_content("test", "text/plain");
  22727. auto cert = req.peer_cert();
  22728. ASSERT_TRUE(static_cast<bool>(cert));
  22729. auto common_name = cert.subject_cn();
  22730. EXPECT_EQ("Common Name", common_name);
  22731. });
  22732. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22733. auto se = detail::scope_exit([&] {
  22734. svr.stop();
  22735. t.join();
  22736. ASSERT_FALSE(svr.is_running());
  22737. });
  22738. svr.wait_until_ready();
  22739. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22740. cli.enable_server_certificate_verification(false);
  22741. cli.set_connection_timeout(30);
  22742. auto res = cli.Get("/test");
  22743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22744. ASSERT_EQ(StatusCode::OK_200, res->status);
  22745. }
  22746. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22747. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22748. // keep-alive SSL session, which reads through that config in
  22749. // mbedtls_ssl_close_notify.
  22750. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22752. ASSERT_TRUE(svr.is_valid());
  22753. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22754. res.set_content("test", "text/plain");
  22755. });
  22756. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22757. auto se = detail::scope_exit([&] {
  22758. svr.stop();
  22759. t.join();
  22760. ASSERT_FALSE(svr.is_running());
  22761. });
  22762. svr.wait_until_ready();
  22763. {
  22764. SSLClient cli(HOST, PORT);
  22765. cli.enable_server_certificate_verification(false);
  22766. cli.set_keep_alive(true);
  22767. auto res = cli.Get("/test");
  22768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22769. ASSERT_EQ(StatusCode::OK_200, res->status);
  22770. // cli is destructed here with the keep-alive SSL session still open.
  22771. }
  22772. }
  22773. #endif
  22774. // WebSocket Tests
  22775. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22776. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22777. // defining the meaning of these bits has been negotiated.
  22778. auto make_frame = [](uint8_t first_byte) {
  22779. std::string frame;
  22780. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22781. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22782. frame += "Hello";
  22783. return frame;
  22784. };
  22785. // RSV1 set (0x40)
  22786. {
  22787. detail::BufferStream strm;
  22788. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22789. ws::Opcode opcode;
  22790. std::string payload;
  22791. bool fin;
  22792. EXPECT_EQ(
  22793. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22794. ws::impl::FrameRead::Fail);
  22795. }
  22796. // RSV2 set (0x20)
  22797. {
  22798. detail::BufferStream strm;
  22799. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22800. ws::Opcode opcode;
  22801. std::string payload;
  22802. bool fin;
  22803. EXPECT_EQ(
  22804. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22805. ws::impl::FrameRead::Fail);
  22806. }
  22807. // RSV3 set (0x10)
  22808. {
  22809. detail::BufferStream strm;
  22810. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22811. ws::Opcode opcode;
  22812. std::string payload;
  22813. bool fin;
  22814. EXPECT_EQ(
  22815. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22816. ws::impl::FrameRead::Fail);
  22817. }
  22818. // No RSV bits set - should succeed
  22819. {
  22820. detail::BufferStream strm;
  22821. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22822. ws::Opcode opcode;
  22823. std::string payload;
  22824. bool fin;
  22825. EXPECT_EQ(
  22826. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22827. ws::impl::FrameRead::Ok);
  22828. EXPECT_EQ(ws::Opcode::Text, opcode);
  22829. EXPECT_EQ("Hello", payload);
  22830. EXPECT_TRUE(fin);
  22831. }
  22832. }
  22833. TEST(WebSocketTest, ControlFrameValidation) {
  22834. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22835. // payload length <= 125.
  22836. // Ping with FIN=0 - must be rejected
  22837. {
  22838. detail::BufferStream strm;
  22839. std::string frame;
  22840. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22841. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22842. strm.write(frame.data(), frame.size());
  22843. ws::Opcode opcode;
  22844. std::string payload;
  22845. bool fin;
  22846. EXPECT_EQ(
  22847. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22848. ws::impl::FrameRead::Fail);
  22849. }
  22850. // Close with FIN=0 - must be rejected
  22851. {
  22852. detail::BufferStream strm;
  22853. std::string frame;
  22854. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22855. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22856. strm.write(frame.data(), frame.size());
  22857. ws::Opcode opcode;
  22858. std::string payload;
  22859. bool fin;
  22860. EXPECT_EQ(
  22861. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22862. ws::impl::FrameRead::Fail);
  22863. }
  22864. // Ping with payload_len=126 (extended length) - must be rejected
  22865. {
  22866. detail::BufferStream strm;
  22867. std::string frame;
  22868. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22869. frame += static_cast<char>(126); // payload_len=126 (>125)
  22870. frame += static_cast<char>(0x00); // extended length high byte
  22871. frame += static_cast<char>(126); // extended length low byte
  22872. frame += std::string(126, 'x');
  22873. strm.write(frame.data(), frame.size());
  22874. ws::Opcode opcode;
  22875. std::string payload;
  22876. bool fin;
  22877. EXPECT_EQ(
  22878. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22879. ws::impl::FrameRead::Fail);
  22880. }
  22881. // Ping with FIN=1 and payload_len=125 - should succeed
  22882. {
  22883. detail::BufferStream strm;
  22884. std::string frame;
  22885. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22886. frame += static_cast<char>(125); // payload_len=125
  22887. frame += std::string(125, 'x');
  22888. strm.write(frame.data(), frame.size());
  22889. ws::Opcode opcode;
  22890. std::string payload;
  22891. bool fin;
  22892. EXPECT_EQ(
  22893. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22894. ws::impl::FrameRead::Ok);
  22895. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22896. EXPECT_EQ(125u, payload.size());
  22897. EXPECT_TRUE(fin);
  22898. }
  22899. }
  22900. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22901. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22902. // length MUST be 0.
  22903. // MSB set - must be rejected
  22904. {
  22905. detail::BufferStream strm;
  22906. std::string frame;
  22907. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22908. frame += static_cast<char>(127); // 64-bit extended length
  22909. frame += static_cast<char>(0x80); // MSB set (invalid)
  22910. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22911. strm.write(frame.data(), frame.size());
  22912. ws::Opcode opcode;
  22913. std::string payload;
  22914. bool fin;
  22915. EXPECT_EQ(
  22916. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22917. ws::impl::FrameRead::Fail);
  22918. }
  22919. // MSB clear - should pass length parsing (will be rejected by max_len,
  22920. // but that's a different check; use a small length to verify)
  22921. {
  22922. detail::BufferStream strm;
  22923. std::string frame;
  22924. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22925. frame += static_cast<char>(127); // 64-bit extended length
  22926. frame += std::string(7, '\0'); // high bytes = 0
  22927. frame += static_cast<char>(0x03); // length = 3
  22928. frame += "abc";
  22929. strm.write(frame.data(), frame.size());
  22930. ws::Opcode opcode;
  22931. std::string payload;
  22932. bool fin;
  22933. EXPECT_EQ(
  22934. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22935. ws::impl::FrameRead::Ok);
  22936. EXPECT_EQ(ws::Opcode::Text, opcode);
  22937. EXPECT_EQ("abc", payload);
  22938. }
  22939. }
  22940. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22941. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22942. // Valid UTF-8
  22943. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22944. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22945. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22946. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22947. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22948. // Invalid UTF-8
  22949. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22950. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22951. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22952. EXPECT_FALSE(
  22953. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22954. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22955. }
  22956. TEST(WebSocketTest, ConnectAndDisconnect) {
  22957. Server svr;
  22958. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22959. std::string msg;
  22960. while (ws.read(msg)) {}
  22961. });
  22962. auto port = svr.bind_to_any_port(HOST);
  22963. std::thread t([&]() { svr.listen_after_bind(); });
  22964. svr.wait_until_ready();
  22965. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22966. auto res = client.connect();
  22967. ASSERT_TRUE(res);
  22968. EXPECT_EQ(Error::Success, res.error());
  22969. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22970. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22971. EXPECT_TRUE(client.is_open());
  22972. client.close();
  22973. EXPECT_FALSE(client.is_open());
  22974. svr.stop();
  22975. t.join();
  22976. }
  22977. TEST(WebSocketTest, ValidURL) {
  22978. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22979. EXPECT_TRUE(ws1.is_valid());
  22980. ws::WebSocketClient ws2("ws://example.com/path");
  22981. EXPECT_TRUE(ws2.is_valid());
  22982. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22983. EXPECT_TRUE(ws3.is_valid());
  22984. #ifdef CPPHTTPLIB_SSL_ENABLED
  22985. ws::WebSocketClient wss1("wss://example.com/path");
  22986. EXPECT_TRUE(wss1.is_valid());
  22987. ws::WebSocketClient wss2("wss://example.com:443/path");
  22988. EXPECT_TRUE(wss2.is_valid());
  22989. #endif
  22990. }
  22991. TEST(WebSocketTest, InvalidURL) {
  22992. // No scheme
  22993. ws::WebSocketClient ws1("localhost:8080/path");
  22994. EXPECT_FALSE(ws1.is_valid());
  22995. // No path
  22996. ws::WebSocketClient ws2("ws://localhost:8080");
  22997. EXPECT_FALSE(ws2.is_valid());
  22998. // Empty string
  22999. ws::WebSocketClient ws3("");
  23000. EXPECT_FALSE(ws3.is_valid());
  23001. // Missing host
  23002. ws::WebSocketClient ws4("ws://:8080/path");
  23003. EXPECT_FALSE(ws4.is_valid());
  23004. // Port number overflow — should not crash
  23005. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23006. EXPECT_FALSE(ws5.is_valid());
  23007. // Port out of range
  23008. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23009. EXPECT_FALSE(ws6.is_valid());
  23010. }
  23011. TEST(WebSocketTest, UnsupportedScheme) {
  23012. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23013. ws::WebSocketClient ws1("http://localhost:8080/path");
  23014. EXPECT_FALSE(ws1.is_valid());
  23015. ws::WebSocketClient ws2("https://localhost:8080/path");
  23016. EXPECT_FALSE(ws2.is_valid());
  23017. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23018. EXPECT_FALSE(ws3.is_valid());
  23019. #else
  23020. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23021. std::invalid_argument);
  23022. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23023. std::invalid_argument);
  23024. #endif
  23025. }
  23026. TEST(WebSocketTest, ConnectWhenInvalid) {
  23027. ws::WebSocketClient ws("not a valid url");
  23028. EXPECT_FALSE(ws.is_valid());
  23029. auto res = ws.connect();
  23030. EXPECT_FALSE(res);
  23031. EXPECT_EQ(Error::Connection, res.error());
  23032. EXPECT_EQ(-1, res.status());
  23033. }
  23034. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23035. // Grab a port that is free, then close it again so nothing listens there
  23036. Server svr;
  23037. auto port = svr.bind_to_any_port(HOST);
  23038. svr.stop();
  23039. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23040. auto res = client.connect();
  23041. ASSERT_FALSE(res);
  23042. EXPECT_EQ(Error::Connection, res.error());
  23043. EXPECT_EQ(-1, res.status());
  23044. }
  23045. TEST(WebSocketTest, DefaultPort) {
  23046. ws::WebSocketClient ws1("ws://example.com/path");
  23047. EXPECT_TRUE(ws1.is_valid());
  23048. // ws:// defaults to port 80 (verified by successful parse)
  23049. #ifdef CPPHTTPLIB_SSL_ENABLED
  23050. ws::WebSocketClient ws2("wss://example.com/path");
  23051. EXPECT_TRUE(ws2.is_valid());
  23052. // wss:// defaults to port 443 (verified by successful parse)
  23053. #endif
  23054. }
  23055. TEST(WebSocketTest, IPv6LiteralAddress) {
  23056. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23057. EXPECT_TRUE(ws1.is_valid());
  23058. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23059. EXPECT_TRUE(ws2.is_valid());
  23060. }
  23061. TEST(WebSocketTest, ComplexPath) {
  23062. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23063. EXPECT_TRUE(ws1.is_valid());
  23064. ws::WebSocketClient ws2("ws://localhost:8080/");
  23065. EXPECT_TRUE(ws2.is_valid());
  23066. }
  23067. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23068. Server svr;
  23069. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23070. std::string msg;
  23071. while (ws.read(msg)) {}
  23072. });
  23073. auto port = svr.bind_to_any_port(HOST);
  23074. std::thread t([&]() { svr.listen_after_bind(); });
  23075. svr.wait_until_ready();
  23076. auto another_host = "example.com";
  23077. auto wrong_ip = "192.0.2.1";
  23078. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23079. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23080. ASSERT_TRUE(client.connect());
  23081. EXPECT_TRUE(client.is_open());
  23082. client.close();
  23083. svr.stop();
  23084. t.join();
  23085. }
  23086. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23087. Server svr;
  23088. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23089. std::string msg;
  23090. while (ws.read(msg)) {}
  23091. });
  23092. auto port = svr.bind_to_any_port(HOST);
  23093. std::thread t([&]() { svr.listen_after_bind(); });
  23094. svr.wait_until_ready();
  23095. auto wrong_ip = "192.0.2.1";
  23096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23097. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23098. client.set_connection_timeout(1);
  23099. client.set_read_timeout(1);
  23100. client.set_write_timeout(1);
  23101. EXPECT_FALSE(client.connect());
  23102. EXPECT_FALSE(client.is_open());
  23103. svr.stop();
  23104. t.join();
  23105. }
  23106. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23107. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23108. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23109. // (RFC 6761) is only a map key and the Host header value.
  23110. auto host = "target.invalid";
  23111. Server svr;
  23112. std::string received_host;
  23113. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23114. received_host = req.get_header_value("Host");
  23115. std::string msg;
  23116. while (ws.read(msg)) {}
  23117. });
  23118. auto port = svr.bind_to_any_port(HOST);
  23119. std::thread t([&]() { svr.listen_after_bind(); });
  23120. // ASSERT_* below returns from the test body, which would leave t joinable
  23121. // and make ~thread call std::terminate.
  23122. auto se = detail::scope_exit([&] {
  23123. svr.stop();
  23124. if (t.joinable()) { t.join(); }
  23125. });
  23126. svr.wait_until_ready();
  23127. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23128. std::to_string(port) + "/ws");
  23129. client.set_hostname_addr_map({{host, HOST}});
  23130. ASSERT_TRUE(client.connect());
  23131. EXPECT_TRUE(client.is_open());
  23132. client.close();
  23133. svr.stop();
  23134. t.join();
  23135. // The mapping only redirects the connection; the identity stays host_.
  23136. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23137. }
  23138. class WebSocketIntegrationTest : public ::testing::Test {
  23139. protected:
  23140. void SetUp() override {
  23141. server_ = httplib::detail::make_unique<Server>();
  23142. setup_server();
  23143. start_server();
  23144. }
  23145. void TearDown() override {
  23146. server_->stop();
  23147. if (server_thread_.joinable()) { server_thread_.join(); }
  23148. }
  23149. void setup_server() {
  23150. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23151. std::string msg;
  23152. ws::ReadResult ret;
  23153. while ((ret = ws.read(msg))) {
  23154. if (ret == ws::Binary) {
  23155. ws.send(msg.data(), msg.size());
  23156. } else {
  23157. ws.send(msg);
  23158. }
  23159. }
  23160. });
  23161. server_->WebSocket("/ws-echo-string",
  23162. [](const Request &, ws::WebSocket &ws) {
  23163. std::string msg;
  23164. while (ws.read(msg)) {
  23165. ws.send("echo: " + msg);
  23166. }
  23167. });
  23168. server_->WebSocket(
  23169. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23170. // Echo back request metadata
  23171. ws.send("path:" + req.path);
  23172. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23173. std::string msg;
  23174. while (ws.read(msg)) {}
  23175. });
  23176. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23177. std::string msg;
  23178. ws.read(msg); // wait for a message
  23179. ws.close();
  23180. });
  23181. server_->WebSocket("/ws-close-status",
  23182. [](const Request &, ws::WebSocket &ws) {
  23183. std::string msg;
  23184. ws.read(msg); // wait for a message
  23185. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23186. });
  23187. server_->WebSocket(
  23188. "/ws-subprotocol",
  23189. [](const Request &, ws::WebSocket &ws) {
  23190. std::string msg;
  23191. while (ws.read(msg)) {
  23192. ws.send(msg);
  23193. }
  23194. },
  23195. [](const std::vector<std::string> &protocols) -> std::string {
  23196. for (const auto &p : protocols) {
  23197. if (p == "graphql-ws") { return p; }
  23198. }
  23199. return "";
  23200. });
  23201. server_->WebSocket(
  23202. "/ws-subprotocol-unoffered",
  23203. [](const Request &, ws::WebSocket &ws) {
  23204. std::string msg;
  23205. while (ws.read(msg)) {
  23206. ws.send(msg);
  23207. }
  23208. },
  23209. [](const std::vector<std::string> &) -> std::string {
  23210. return "admin";
  23211. });
  23212. }
  23213. void start_server() {
  23214. port_ = server_->bind_to_any_port(HOST);
  23215. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23216. server_->wait_until_ready();
  23217. }
  23218. std::unique_ptr<Server> server_;
  23219. std::thread server_thread_;
  23220. int port_ = 0;
  23221. };
  23222. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23224. "/ws-echo");
  23225. ASSERT_TRUE(client.connect());
  23226. ASSERT_TRUE(client.is_open());
  23227. ASSERT_TRUE(client.send("Hello WebSocket"));
  23228. std::string msg;
  23229. EXPECT_EQ(ws::Text, client.read(msg));
  23230. EXPECT_EQ("Hello WebSocket", msg);
  23231. client.close();
  23232. }
  23233. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23234. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23235. "/ws-echo");
  23236. ASSERT_TRUE(client.connect());
  23237. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23238. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23239. std::string msg;
  23240. EXPECT_EQ(ws::Binary, client.read(msg));
  23241. EXPECT_EQ(binary_data, msg);
  23242. client.close();
  23243. }
  23244. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23245. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23246. "/ws-echo");
  23247. ASSERT_TRUE(client.connect());
  23248. for (int i = 0; i < 10; i++) {
  23249. auto text = "message " + std::to_string(i);
  23250. ASSERT_TRUE(client.send(text));
  23251. std::string msg;
  23252. ASSERT_TRUE(client.read(msg));
  23253. EXPECT_EQ(text, msg);
  23254. }
  23255. client.close();
  23256. }
  23257. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23259. "/ws-close");
  23260. ASSERT_TRUE(client.connect());
  23261. // Send a message to trigger the server to close
  23262. ASSERT_TRUE(client.send("trigger close"));
  23263. // The server will close, so read should return false
  23264. std::string msg;
  23265. EXPECT_FALSE(client.read(msg));
  23266. EXPECT_FALSE(client.is_open());
  23267. }
  23268. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23270. "/ws-echo");
  23271. ASSERT_TRUE(client.connect());
  23272. // 128KB message
  23273. std::string large_data(128 * 1024, 'X');
  23274. ASSERT_TRUE(client.send(large_data));
  23275. std::string msg;
  23276. ASSERT_TRUE(client.read(msg));
  23277. EXPECT_EQ(large_data, msg);
  23278. client.close();
  23279. }
  23280. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23282. "/ws-echo");
  23283. ASSERT_TRUE(client.connect());
  23284. const int num_threads = 4;
  23285. std::vector<std::thread> threads;
  23286. std::atomic<int> send_count{0};
  23287. for (int t = 0; t < num_threads; t++) {
  23288. threads.emplace_back([&client, &send_count, t]() {
  23289. for (int i = 0; i < 5; i++) {
  23290. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23291. if (client.send(text)) { send_count++; }
  23292. }
  23293. });
  23294. }
  23295. for (auto &th : threads) {
  23296. th.join();
  23297. }
  23298. int received = 0;
  23299. std::string msg;
  23300. while (received < send_count.load()) {
  23301. if (!client.read(msg)) { break; }
  23302. received++;
  23303. }
  23304. EXPECT_EQ(send_count.load(), received);
  23305. client.close();
  23306. }
  23307. TEST_F(WebSocketIntegrationTest, ReadString) {
  23308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23309. "/ws-echo-string");
  23310. ASSERT_TRUE(client.connect());
  23311. ASSERT_TRUE(client.send("hello"));
  23312. std::string msg;
  23313. ASSERT_TRUE(client.read(msg));
  23314. EXPECT_EQ("echo: hello", msg);
  23315. ASSERT_TRUE(client.send("world"));
  23316. ASSERT_TRUE(client.read(msg));
  23317. EXPECT_EQ("echo: world", msg);
  23318. client.close();
  23319. }
  23320. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23321. Headers headers = {{"X-Test-Header", "test-value"}};
  23322. ws::WebSocketClient client(
  23323. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23324. ASSERT_TRUE(client.connect());
  23325. std::string msg;
  23326. ASSERT_TRUE(client.read(msg));
  23327. EXPECT_EQ("path:/ws-request-info", msg);
  23328. ASSERT_TRUE(client.read(msg));
  23329. EXPECT_EQ("header:test-value", msg);
  23330. client.close();
  23331. }
  23332. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23334. "/ws-echo");
  23335. client.set_read_timeout(1, 0); // 1 second
  23336. ASSERT_TRUE(client.connect());
  23337. // Don't send anything — server echo handler waits for a message, so read()
  23338. // should time out. The connection survives it: nothing was consumed.
  23339. std::string msg;
  23340. EXPECT_EQ(client.read(msg), ws::Timeout);
  23341. EXPECT_TRUE(client.is_open());
  23342. // And it is still usable afterwards.
  23343. EXPECT_TRUE(client.send("after timeout"));
  23344. EXPECT_EQ(client.read(msg), ws::Text);
  23345. EXPECT_EQ(msg, "after timeout");
  23346. }
  23347. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23349. "/ws-echo");
  23350. client.set_read_timeout(1, 0);
  23351. ASSERT_TRUE(client.connect());
  23352. ASSERT_TRUE(client.send("first"));
  23353. std::string msg;
  23354. ASSERT_EQ(client.read(msg), ws::Text);
  23355. ASSERT_EQ(msg, "first");
  23356. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23357. // not be used with a read timeout: it would reprocess the previous message.
  23358. EXPECT_EQ(client.read(msg), ws::Timeout);
  23359. EXPECT_EQ(msg, "first");
  23360. }
  23361. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23362. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23363. "/ws-echo");
  23364. ASSERT_TRUE(client.connect());
  23365. // Setting it once the connection is open reaches the live stream, not just
  23366. // the seed for the next connect().
  23367. client.set_read_timeout(1, 0);
  23368. std::string msg;
  23369. EXPECT_EQ(client.read(msg), ws::Timeout);
  23370. EXPECT_TRUE(client.is_open());
  23371. }
  23372. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23373. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23374. "/ws-echo");
  23375. client.set_read_timeout(5, 0);
  23376. ASSERT_TRUE(client.connect());
  23377. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23378. // The server should reject it and close the connection.
  23379. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23380. client.send(oversized);
  23381. // The server's read() should have failed due to payload limit,
  23382. // so our read() should return false (connection closed).
  23383. std::string msg;
  23384. EXPECT_FALSE(client.read(msg));
  23385. }
  23386. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23388. "/ws-echo");
  23389. client.set_read_timeout(10, 0);
  23390. ASSERT_TRUE(client.connect());
  23391. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23392. // This should succeed.
  23393. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23394. ASSERT_TRUE(client.send(at_limit));
  23395. std::string msg;
  23396. ASSERT_TRUE(client.read(msg));
  23397. EXPECT_EQ(at_limit.size(), msg.size());
  23398. client.close();
  23399. }
  23400. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23401. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23402. "/nonexistent");
  23403. auto res = client.connect();
  23404. EXPECT_FALSE(res);
  23405. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23406. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23407. EXPECT_FALSE(client.is_open());
  23408. }
  23409. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23411. "/ws-echo");
  23412. ASSERT_TRUE(client.connect());
  23413. ASSERT_TRUE(client.send(""));
  23414. std::string msg;
  23415. EXPECT_EQ(ws::Text, client.read(msg));
  23416. EXPECT_EQ("", msg);
  23417. client.close();
  23418. }
  23419. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23420. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23421. "/ws-echo");
  23422. // First connection
  23423. ASSERT_TRUE(client.connect());
  23424. ASSERT_TRUE(client.send("first"));
  23425. std::string msg;
  23426. ASSERT_TRUE(client.read(msg));
  23427. EXPECT_EQ("first", msg);
  23428. client.close();
  23429. EXPECT_FALSE(client.is_open());
  23430. // Reconnect using the same client object
  23431. ASSERT_TRUE(client.connect());
  23432. ASSERT_TRUE(client.is_open());
  23433. ASSERT_TRUE(client.send("second"));
  23434. ASSERT_TRUE(client.read(msg));
  23435. EXPECT_EQ("second", msg);
  23436. client.close();
  23437. }
  23438. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23440. "/ws-close-status");
  23441. ASSERT_TRUE(client.connect());
  23442. // Trigger the server to close with GoingAway status
  23443. ASSERT_TRUE(client.send("trigger"));
  23444. // read() should return false after receiving the close frame
  23445. std::string msg;
  23446. EXPECT_FALSE(client.read(msg));
  23447. EXPECT_FALSE(client.is_open());
  23448. }
  23449. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23451. "/ws-echo");
  23452. ASSERT_TRUE(client.connect());
  23453. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23454. EXPECT_FALSE(client.is_open());
  23455. }
  23456. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23457. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23458. ws::WebSocketClient client(
  23459. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23460. ASSERT_TRUE(client.connect());
  23461. // Server should have selected graphql-ws
  23462. EXPECT_EQ("graphql-ws", client.subprotocol());
  23463. client.close();
  23464. }
  23465. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23466. Headers headers;
  23467. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23468. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23469. ws::WebSocketClient client(
  23470. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23471. ASSERT_TRUE(client.connect());
  23472. // The offer on the second field line counts too, so graphql-ws is selected
  23473. EXPECT_EQ("graphql-ws", client.subprotocol());
  23474. client.close();
  23475. }
  23476. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23477. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23478. ws::WebSocketClient client(
  23479. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23480. ASSERT_TRUE(client.connect());
  23481. // Server should not have selected any subprotocol
  23482. EXPECT_TRUE(client.subprotocol().empty());
  23483. client.close();
  23484. }
  23485. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23486. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23487. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23488. "/ws-subprotocol-unoffered",
  23489. headers);
  23490. ASSERT_TRUE(client.connect());
  23491. EXPECT_TRUE(client.subprotocol().empty());
  23492. client.close();
  23493. }
  23494. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23495. // Connect without requesting any subprotocol
  23496. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23497. "/ws-subprotocol");
  23498. ASSERT_TRUE(client.connect());
  23499. EXPECT_TRUE(client.subprotocol().empty());
  23500. client.close();
  23501. }
  23502. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23504. "/ws-echo");
  23505. client.set_tcp_nodelay(true);
  23506. client.set_connection_timeout(3, 0);
  23507. bool socket_options_called = false;
  23508. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23509. ASSERT_TRUE(client.connect());
  23510. ASSERT_TRUE(client.is_open());
  23511. EXPECT_TRUE(socket_options_called);
  23512. ASSERT_TRUE(client.send("hello"));
  23513. std::string msg;
  23514. auto result = client.read(msg);
  23515. EXPECT_EQ(result, ws::ReadResult::Text);
  23516. EXPECT_EQ(msg, "hello");
  23517. client.close();
  23518. }
  23519. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23520. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23521. "/ws-echo");
  23522. client.set_connection_timeout(std::chrono::seconds(3));
  23523. client.set_write_timeout(std::chrono::seconds(3));
  23524. // A sub-second remainder exercises the seconds/microseconds split.
  23525. client.set_read_timeout(std::chrono::milliseconds(1500));
  23526. ASSERT_TRUE(client.connect());
  23527. auto start = std::chrono::steady_clock::now();
  23528. std::string msg;
  23529. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23530. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23531. std::chrono::steady_clock::now() - start)
  23532. .count();
  23533. // Above 1s so that dropping the microseconds half of the split fails here.
  23534. // Ignoring the setter altogether would not reach this line at all: a client
  23535. // waits forever by default.
  23536. EXPECT_GE(elapsed, 1400);
  23537. EXPECT_LT(elapsed, 30000);
  23538. }
  23539. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23540. Server svr;
  23541. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23542. if (!req.has_header("Authorization")) {
  23543. res.status = StatusCode::Unauthorized_401;
  23544. res.set_content("Unauthorized", "text/plain");
  23545. return Server::HandlerResponse::Handled;
  23546. }
  23547. return Server::HandlerResponse::Unhandled;
  23548. });
  23549. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23550. std::string msg;
  23551. while (ws.read(msg)) {
  23552. ws.send(msg);
  23553. }
  23554. });
  23555. auto port = svr.bind_to_any_port("localhost");
  23556. std::thread t([&]() { svr.listen_after_bind(); });
  23557. svr.wait_until_ready();
  23558. // Without Authorization header - should be rejected before upgrade
  23559. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23560. EXPECT_FALSE(client1.connect());
  23561. // The rejection is framed like any other HTTP response
  23562. {
  23563. Client cli("localhost", port);
  23564. Headers headers = {{"Upgrade", "websocket"},
  23565. {"Connection", "Upgrade"},
  23566. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23567. {"Sec-WebSocket-Version", "13"}};
  23568. auto res = cli.Get("/ws", headers);
  23569. ASSERT_TRUE(res);
  23570. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23571. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23572. EXPECT_EQ("Unauthorized", res->body);
  23573. }
  23574. // With Authorization header - should succeed
  23575. Headers headers = {{"Authorization", "Bearer token123"}};
  23576. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23577. headers);
  23578. ASSERT_TRUE(client2.connect());
  23579. ASSERT_TRUE(client2.send("hello"));
  23580. std::string msg;
  23581. ASSERT_TRUE(client2.read(msg));
  23582. EXPECT_EQ("hello", msg);
  23583. client2.close();
  23584. svr.stop();
  23585. t.join();
  23586. }
  23587. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23588. Server svr;
  23589. std::atomic<int> pre_routing_calls{0};
  23590. std::atomic<int> pre_request_calls{0};
  23591. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23592. pre_routing_calls++;
  23593. if (req.path == "/handled") {
  23594. res.set_content("handled", "text/plain");
  23595. return Server::HandlerResponse::Handled;
  23596. }
  23597. return Server::HandlerResponse::Unhandled;
  23598. });
  23599. svr.set_pre_request_handler([&](const Request &, Response &) {
  23600. pre_request_calls++;
  23601. return Server::HandlerResponse::Unhandled;
  23602. });
  23603. svr.Get("/http", [](const Request &, Response &res) {
  23604. res.set_content("http", "text/plain");
  23605. });
  23606. svr.WebSocket("/ws",
  23607. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23608. auto port = svr.bind_to_any_port("localhost");
  23609. std::thread t([&]() { svr.listen_after_bind(); });
  23610. auto se = detail::scope_exit([&] {
  23611. svr.stop();
  23612. t.join();
  23613. });
  23614. svr.wait_until_ready();
  23615. Headers upgrade = {{"Upgrade", "websocket"},
  23616. {"Connection", "Upgrade"},
  23617. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23618. {"Sec-WebSocket-Version", "13"}};
  23619. auto get = [&](const char *path) {
  23620. pre_routing_calls = 0;
  23621. return Client("localhost", port).Get(path, upgrade);
  23622. };
  23623. // No WebSocket route, but an HTTP one
  23624. auto res = get("/http");
  23625. ASSERT_TRUE(res);
  23626. EXPECT_EQ(StatusCode::OK_200, res->status);
  23627. EXPECT_EQ("http", res->body);
  23628. EXPECT_EQ(1, pre_routing_calls);
  23629. EXPECT_EQ(1, pre_request_calls);
  23630. // No route at all
  23631. res = get("/none");
  23632. ASSERT_TRUE(res);
  23633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23634. EXPECT_EQ(1, pre_routing_calls);
  23635. // Answered by the pre-routing handler
  23636. res = get("/handled");
  23637. ASSERT_TRUE(res);
  23638. EXPECT_EQ(StatusCode::OK_200, res->status);
  23639. EXPECT_EQ("handled", res->body);
  23640. EXPECT_EQ(1, pre_routing_calls);
  23641. // A WebSocket route
  23642. pre_routing_calls = 0;
  23643. pre_request_calls = 0;
  23644. {
  23645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23646. "/ws");
  23647. ASSERT_TRUE(client.connect());
  23648. std::string msg;
  23649. ASSERT_TRUE(client.read(msg));
  23650. EXPECT_EQ("ws", msg);
  23651. client.close();
  23652. }
  23653. EXPECT_EQ(1, pre_routing_calls);
  23654. EXPECT_EQ(1, pre_request_calls);
  23655. }
  23656. // An upgrade request answered by a hook leaves its body unread, so that body
  23657. // must not be served as the next request on the connection.
  23658. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23659. Server svr;
  23660. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23661. if (req.path == "/pre-routing") {
  23662. res.set_content("pre-routing", "text/plain");
  23663. return Server::HandlerResponse::Handled;
  23664. }
  23665. return Server::HandlerResponse::Unhandled;
  23666. });
  23667. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23668. if (req.matched_route == "/pre-request") {
  23669. res.set_content("pre-request", "text/plain");
  23670. return Server::HandlerResponse::Handled;
  23671. }
  23672. return Server::HandlerResponse::Unhandled;
  23673. });
  23674. svr.Get("/smuggled", [](const Request &, Response &res) {
  23675. res.set_content("smuggled", "text/plain");
  23676. });
  23677. svr.WebSocket("/pre-request",
  23678. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23679. auto port = svr.bind_to_any_port(HOST);
  23680. std::thread t([&]() { svr.listen_after_bind(); });
  23681. auto se = detail::scope_exit([&] {
  23682. svr.stop();
  23683. t.join();
  23684. });
  23685. svr.wait_until_ready();
  23686. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23687. for (auto path : {"/pre-routing", "/pre-request"}) {
  23688. std::string req = std::string("GET ") + path +
  23689. " HTTP/1.1\r\n"
  23690. "Host: localhost\r\n"
  23691. "Upgrade: websocket\r\n"
  23692. "Connection: Upgrade\r\n"
  23693. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23694. "Sec-WebSocket-Version: 13\r\n"
  23695. "Content-Length: " +
  23696. std::to_string(body.size()) + "\r\n\r\n" + body;
  23697. std::string res;
  23698. ASSERT_TRUE(send_request(5, req, &res, port));
  23699. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23700. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23701. // Only one response, and the body was not served as a request
  23702. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23703. }
  23704. }
  23705. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23706. Server svr;
  23707. std::atomic<int> pre_request_calls{0};
  23708. std::atomic<bool> route_matched{false};
  23709. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23710. pre_request_calls++;
  23711. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23712. if (req.get_header_value("Authorization") != "Bearer token123") {
  23713. res.status = StatusCode::Unauthorized_401;
  23714. res.set_content("Unauthorized", "text/plain");
  23715. return Server::HandlerResponse::Handled;
  23716. }
  23717. return Server::HandlerResponse::Unhandled;
  23718. });
  23719. std::atomic<bool> handler_called{false};
  23720. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23721. handler_called = true;
  23722. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23723. });
  23724. auto port = svr.bind_to_any_port("localhost");
  23725. std::thread t([&]() { svr.listen_after_bind(); });
  23726. svr.wait_until_ready();
  23727. // Without Authorization header - should be rejected before upgrade
  23728. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23729. "/ws/1");
  23730. EXPECT_FALSE(client1.connect());
  23731. EXPECT_FALSE(handler_called);
  23732. EXPECT_EQ(1, pre_request_calls);
  23733. EXPECT_TRUE(route_matched);
  23734. // The rejection is an ordinary HTTP response, not a protocol switch
  23735. {
  23736. Client cli("localhost", port);
  23737. Headers headers = {{"Upgrade", "websocket"},
  23738. {"Connection", "Upgrade"},
  23739. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23740. {"Sec-WebSocket-Version", "13"}};
  23741. auto res = cli.Get("/ws/1", headers);
  23742. ASSERT_TRUE(res);
  23743. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23744. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23745. EXPECT_EQ("Unauthorized", res->body);
  23746. }
  23747. EXPECT_FALSE(handler_called);
  23748. // With Authorization header - should succeed
  23749. Headers headers = {{"Authorization", "Bearer token123"}};
  23750. ws::WebSocketClient client2(
  23751. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23752. ASSERT_TRUE(client2.connect());
  23753. std::string msg;
  23754. ASSERT_TRUE(client2.read(msg));
  23755. EXPECT_EQ("/ws/:id 2", msg);
  23756. EXPECT_TRUE(handler_called);
  23757. client2.close();
  23758. svr.stop();
  23759. t.join();
  23760. }
  23761. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23762. Server svr;
  23763. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23764. // A read timeout is how a handler gets control back. Without it, a handler
  23765. // parked in read() can never write on the connection it is reading.
  23766. ws.set_read_timeout(std::chrono::milliseconds(100));
  23767. std::string msg;
  23768. while (ws.is_open()) {
  23769. auto r = ws.read(msg);
  23770. if (r == httplib::ws::Timeout) {
  23771. ws.send("tick");
  23772. continue;
  23773. }
  23774. if (r == httplib::ws::Fail) { break; }
  23775. ws.send(msg);
  23776. }
  23777. });
  23778. auto port = svr.bind_to_any_port("localhost");
  23779. std::thread t([&]() { svr.listen_after_bind(); });
  23780. svr.wait_until_ready();
  23781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23782. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23783. ASSERT_TRUE(client.connect());
  23784. // The client sends nothing, so anything it receives came out of the
  23785. // handler's timeout path.
  23786. std::string msg;
  23787. ASSERT_EQ(client.read(msg), ws::Text);
  23788. EXPECT_EQ("tick", msg);
  23789. client.close();
  23790. svr.stop();
  23791. t.join();
  23792. }
  23793. // Stream::read may return fewer bytes than asked for. This is that contract at
  23794. // its worst -- one byte per call -- which is what a frame header straddling a
  23795. // read buffer's boundary looks like to the frame parser.
  23796. class WsByteAtATimeStream : public Stream {
  23797. public:
  23798. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23799. bool is_readable() const override { return true; }
  23800. bool wait_readable() const override { return true; }
  23801. bool wait_writable() const override { return true; }
  23802. ssize_t read(char *ptr, size_t size) override {
  23803. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23804. *ptr = data_[pos_++];
  23805. return 1;
  23806. }
  23807. ssize_t write(const char *, size_t size) override {
  23808. return static_cast<ssize_t>(size);
  23809. }
  23810. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23811. ip = "127.0.0.1";
  23812. port = 0;
  23813. }
  23814. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23815. ip = "127.0.0.1";
  23816. port = 0;
  23817. }
  23818. socket_t socket() const override { return INVALID_SOCKET; }
  23819. time_t duration() const override { return 0; }
  23820. private:
  23821. std::string data_;
  23822. size_t pos_ = 0;
  23823. };
  23824. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23825. // The payload uses the 16-bit extended length, so the header, the length
  23826. // and the mask key are all multi-byte fields here. Each used to be read
  23827. // with a single read() call, which fails as soon as one is split. The
  23828. // payload is also a little over one read chunk, so it is read in two.
  23829. std::string body;
  23830. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23831. body += static_cast<char>(i % 251);
  23832. }
  23833. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23834. std::string frame;
  23835. frame += static_cast<char>(0x81); // FIN + Text
  23836. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23837. frame += static_cast<char>(body.size() >> 8);
  23838. frame += static_cast<char>(body.size() & 0xff);
  23839. for (size_t i = 0; i < 4; i++) {
  23840. frame += static_cast<char>(mask[i]);
  23841. }
  23842. for (size_t i = 0; i < body.size(); i++) {
  23843. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23844. }
  23845. WsByteAtATimeStream strm(frame);
  23846. ws::Opcode opcode;
  23847. std::string payload;
  23848. bool fin = false;
  23849. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23850. /*expect_masked=*/true, body.size()),
  23851. ws::impl::FrameRead::Ok);
  23852. EXPECT_TRUE(fin);
  23853. EXPECT_EQ(opcode, ws::Opcode::Text);
  23854. EXPECT_EQ(payload, body);
  23855. }
  23856. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23857. std::string body(2000, 'x');
  23858. std::string frame;
  23859. frame += static_cast<char>(0x82); // FIN + Binary
  23860. frame += static_cast<char>(126); // 16-bit length follows
  23861. frame += static_cast<char>(body.size() >> 8);
  23862. frame += static_cast<char>(body.size() & 0xff);
  23863. frame += body;
  23864. detail::BufferStream strm;
  23865. strm.write(frame.data(), frame.size());
  23866. ws::Opcode opcode;
  23867. std::string payload;
  23868. bool fin;
  23869. EXPECT_EQ(
  23870. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23871. ws::impl::FrameRead::Ok);
  23872. EXPECT_EQ(body, payload);
  23873. }
  23874. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23875. // The header announces the largest payload allowed, and only 3 bytes of it
  23876. // ever arrive.
  23877. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23878. std::string frame;
  23879. frame += static_cast<char>(0x82); // FIN + Binary
  23880. frame += static_cast<char>(127); // 64-bit length follows
  23881. for (int shift = 56; shift >= 0; shift -= 8) {
  23882. frame += static_cast<char>((len >> shift) & 0xff);
  23883. }
  23884. frame += "abc";
  23885. detail::BufferStream strm;
  23886. strm.write(frame.data(), frame.size());
  23887. ws::Opcode opcode;
  23888. std::string payload;
  23889. bool fin;
  23890. EXPECT_EQ(
  23891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23892. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23893. ws::impl::FrameRead::Fail);
  23894. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23895. }
  23896. TEST(WebSocketTest, QueryStringInHandshake) {
  23897. Server svr;
  23898. std::mutex mtx;
  23899. std::string received_target;
  23900. std::string received_token;
  23901. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23902. {
  23903. std::lock_guard<std::mutex> lock(mtx);
  23904. received_target = req.target;
  23905. if (req.has_param("token")) {
  23906. received_token = req.get_param_value("token");
  23907. }
  23908. }
  23909. std::string msg;
  23910. while (ws.read(msg)) {
  23911. ws.send(msg);
  23912. }
  23913. });
  23914. auto port = svr.bind_to_any_port("localhost");
  23915. std::thread t([&]() { svr.listen_after_bind(); });
  23916. svr.wait_until_ready();
  23917. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23918. "/ws?token=ABC&session=123");
  23919. ASSERT_TRUE(client.connect());
  23920. // Round-trip ensures the handler has run and captured the request.
  23921. ASSERT_TRUE(client.send("hello"));
  23922. std::string msg;
  23923. ASSERT_TRUE(client.read(msg));
  23924. EXPECT_EQ("hello", msg);
  23925. client.close();
  23926. {
  23927. std::lock_guard<std::mutex> lock(mtx);
  23928. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23929. EXPECT_EQ("ABC", received_token);
  23930. }
  23931. svr.stop();
  23932. t.join();
  23933. }
  23934. // Run a handshake against a throwaway server and hand the request the server
  23935. // received back to the caller, so tests can assert on the headers the client
  23936. // actually put on the wire.
  23937. static void capture_websocket_handshake_request(
  23938. const Headers &client_headers,
  23939. std::function<void(const Request &, int port)> verify) {
  23940. Server svr;
  23941. std::mutex mtx;
  23942. Request received;
  23943. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23944. {
  23945. std::lock_guard<std::mutex> lock(mtx);
  23946. received = req;
  23947. }
  23948. std::string msg;
  23949. while (ws.read(msg)) {
  23950. ws.send(msg);
  23951. }
  23952. });
  23953. auto port = svr.bind_to_any_port("localhost");
  23954. std::thread t([&]() { svr.listen_after_bind(); });
  23955. auto se = detail::scope_exit([&] {
  23956. svr.stop();
  23957. t.join();
  23958. });
  23959. svr.wait_until_ready();
  23960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23961. client_headers);
  23962. ASSERT_TRUE(client.connect());
  23963. ASSERT_TRUE(client.send("hello"));
  23964. std::string msg;
  23965. ASSERT_TRUE(client.read(msg));
  23966. client.close();
  23967. {
  23968. std::lock_guard<std::mutex> lock(mtx);
  23969. verify(received, port);
  23970. }
  23971. }
  23972. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23973. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23974. // Non-default port must be present in the Host header. Default ports
  23975. // (80/443) are omitted; that logic is covered by
  23976. // MakeHostAndPortStringTest.
  23977. EXPECT_EQ("localhost:" + std::to_string(port),
  23978. req.get_header_value("Host"));
  23979. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23980. req.get_header_value("User-Agent"));
  23981. EXPECT_FALSE(req.has_header("Accept"));
  23982. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23983. EXPECT_FALSE(req.has_header("Content-Length"));
  23984. });
  23985. }
  23986. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23987. capture_websocket_handshake_request(
  23988. {{"Host", "example.com"},
  23989. {"User-Agent", "custom-agent"},
  23990. {"X-Custom", "value"}},
  23991. [](const Request &req, int) {
  23992. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23993. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23994. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23995. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23996. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23997. });
  23998. }
  23999. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24000. capture_websocket_handshake_request(
  24001. {{"Upgrade", "bogus"},
  24002. {"Connection", "close"},
  24003. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24004. {"Sec-WebSocket-Version", "8"}},
  24005. [](const Request &req, int) {
  24006. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24007. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24008. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24009. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24010. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24011. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24012. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24013. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24014. req.get_header_value("Sec-WebSocket-Key"));
  24015. });
  24016. }
  24017. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24018. // A header the client refuses to send must abort the handshake before any
  24019. // part of it reaches the wire; a lone request line would otherwise sit in
  24020. // the peer's buffer as a truncated request.
  24021. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24022. ASSERT_NE(INVALID_SOCKET, srv);
  24023. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24024. sockaddr_in addr{};
  24025. addr.sin_family = AF_INET;
  24026. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24027. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24028. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24029. ASSERT_EQ(0, ::listen(srv, 1));
  24030. sockaddr_in bound{};
  24031. socklen_t bound_len = sizeof(bound);
  24032. ASSERT_EQ(
  24033. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24034. auto port = ntohs(bound.sin_port);
  24035. ssize_t received = -1;
  24036. std::thread t([&] {
  24037. // Bound every blocking call so a regression fails the test with a bad
  24038. // value instead of hanging the suite.
  24039. fd_set rfds;
  24040. FD_ZERO(&rfds);
  24041. FD_SET(srv, &rfds);
  24042. timeval tv{5, 0};
  24043. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24044. 0) {
  24045. return;
  24046. }
  24047. sockaddr_in cli_addr{};
  24048. socklen_t cli_len = sizeof(cli_addr);
  24049. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24050. if (cli == INVALID_SOCKET) { return; }
  24051. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24052. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24053. char buf[4096];
  24054. received = ::recv(cli, buf, sizeof(buf), 0);
  24055. });
  24056. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24057. // connect() has already shut the socket down by the time it returns false,
  24058. // so the peer sees EOF without waiting for the client to be destroyed.
  24059. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24060. {{"X-Bad", "a\r\nInjected: 1"}});
  24061. EXPECT_FALSE(client.connect());
  24062. t.join();
  24063. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24064. EXPECT_EQ(0, received);
  24065. }
  24066. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24067. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24068. // contains "upgrade" as a substring is a different token and must not
  24069. // start a WebSocket handshake.
  24070. auto make_request = [](const std::vector<std::string> &connection_values) {
  24071. Request req;
  24072. req.method = "GET";
  24073. req.headers.emplace("Upgrade", "websocket");
  24074. for (const auto &value : connection_values) {
  24075. req.headers.emplace("Connection", value);
  24076. }
  24077. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24078. req.headers.emplace("Sec-WebSocket-Version", "13");
  24079. return req;
  24080. };
  24081. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24082. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24083. EXPECT_TRUE(
  24084. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24085. EXPECT_TRUE(
  24086. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24087. EXPECT_TRUE(
  24088. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24089. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24090. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24091. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24092. EXPECT_FALSE(
  24093. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24094. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24095. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24096. }
  24097. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24098. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24099. // asks recipients to match each protocol-name case-insensitively, and RFC
  24100. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24101. // client naming websocket alongside another protocol, or on a second field
  24102. // line, is offering websocket; a value that merely contains "websocket" as a
  24103. // substring is a different protocol name and is not.
  24104. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24105. Request req;
  24106. req.method = "GET";
  24107. for (const auto &value : upgrade_values) {
  24108. req.headers.emplace("Upgrade", value);
  24109. }
  24110. req.headers.emplace("Connection", "Upgrade");
  24111. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24112. req.headers.emplace("Sec-WebSocket-Version", "13");
  24113. return req;
  24114. };
  24115. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24116. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24117. EXPECT_TRUE(
  24118. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24119. EXPECT_TRUE(
  24120. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24121. EXPECT_TRUE(
  24122. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24123. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24124. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24125. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24126. EXPECT_FALSE(
  24127. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24128. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24129. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24130. }
  24131. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24132. Server svr;
  24133. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24134. auto port = svr.bind_to_any_port("localhost");
  24135. std::thread t([&]() { svr.listen_after_bind(); });
  24136. auto se = detail::scope_exit([&] {
  24137. svr.stop();
  24138. t.join();
  24139. });
  24140. svr.wait_until_ready();
  24141. Headers headers = {{"Upgrade", "websocket"},
  24142. {"Connection", "notupgrade"},
  24143. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24144. {"Sec-WebSocket-Version", "13"}};
  24145. Client cli("localhost", port);
  24146. auto res = cli.Get("/ws", headers);
  24147. // The route exists only as a WebSocket route, so a request that fails the
  24148. // handshake check falls through to ordinary routing.
  24149. ASSERT_TRUE(res);
  24150. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24151. }
  24152. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24153. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24154. // Connection value is the only thing left for the client to reject.
  24155. Server svr;
  24156. svr.Get("/ws", [](const Request &req, Response &res) {
  24157. res.status = StatusCode::SwitchingProtocol_101;
  24158. res.set_header("Upgrade", "websocket");
  24159. res.set_header("Connection", "notupgrade");
  24160. res.set_header("Sec-WebSocket-Accept",
  24161. detail::websocket_accept_key(
  24162. req.get_header_value("Sec-WebSocket-Key")));
  24163. });
  24164. auto port = svr.bind_to_any_port("localhost");
  24165. std::thread t([&]() { svr.listen_after_bind(); });
  24166. auto se = detail::scope_exit([&] {
  24167. svr.stop();
  24168. t.join();
  24169. });
  24170. svr.wait_until_ready();
  24171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24172. auto res = client.connect();
  24173. EXPECT_FALSE(res);
  24174. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24175. EXPECT_FALSE(client.is_open());
  24176. }
  24177. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24178. Server svr;
  24179. svr.Get("/ws", [](const Request &req, Response &res) {
  24180. res.status = StatusCode::SwitchingProtocol_101;
  24181. res.set_header("Upgrade", "websocket");
  24182. res.set_header("Connection", "Upgrade");
  24183. res.set_header("Sec-WebSocket-Accept",
  24184. detail::websocket_accept_key(
  24185. req.get_header_value("Sec-WebSocket-Key")));
  24186. res.set_header("Sec-WebSocket-Protocol", "admin");
  24187. });
  24188. auto port = svr.bind_to_any_port("localhost");
  24189. std::thread t([&]() { svr.listen_after_bind(); });
  24190. auto se = detail::scope_exit([&] {
  24191. svr.stop();
  24192. t.join();
  24193. });
  24194. svr.wait_until_ready();
  24195. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24196. // Server selects a subprotocol the client never offered
  24197. {
  24198. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24199. ws::WebSocketClient client(url, headers);
  24200. auto res = client.connect();
  24201. EXPECT_FALSE(res);
  24202. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24203. EXPECT_FALSE(client.is_open());
  24204. EXPECT_TRUE(client.subprotocol().empty());
  24205. }
  24206. // Client offered none but the server named one anyway
  24207. {
  24208. ws::WebSocketClient client(url);
  24209. auto res = client.connect();
  24210. EXPECT_FALSE(res);
  24211. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24212. EXPECT_FALSE(client.is_open());
  24213. EXPECT_TRUE(client.subprotocol().empty());
  24214. }
  24215. }
  24216. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24217. // The socket path doubles as the URL host, so it must not contain '/'.
  24218. const char *shard = getenv("GTEST_SHARD_INDEX");
  24219. const std::string sock_path =
  24220. shard ? std::string("httplib-ws-") + shard + ".sock"
  24221. : std::string("httplib-ws.sock");
  24222. std::remove(sock_path.c_str());
  24223. Server svr;
  24224. std::mutex mtx;
  24225. std::string received_host;
  24226. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24227. {
  24228. std::lock_guard<std::mutex> lock(mtx);
  24229. received_host = req.get_header_value("Host");
  24230. }
  24231. std::string msg;
  24232. while (ws.read(msg)) {
  24233. ws.send(msg);
  24234. }
  24235. });
  24236. svr.set_address_family(AF_UNIX);
  24237. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24238. auto se = detail::scope_exit([&] {
  24239. svr.stop();
  24240. t.join();
  24241. std::remove(sock_path.c_str());
  24242. });
  24243. svr.wait_until_ready();
  24244. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24245. client.set_address_family(AF_UNIX);
  24246. ASSERT_TRUE(client.connect());
  24247. ASSERT_TRUE(client.send("hello"));
  24248. std::string msg;
  24249. ASSERT_TRUE(client.read(msg));
  24250. client.close();
  24251. {
  24252. std::lock_guard<std::mutex> lock(mtx);
  24253. // There is no host:port for a Unix socket, so the same "localhost"
  24254. // placeholder the HTTP client uses is expected.
  24255. EXPECT_EQ("localhost", received_host);
  24256. }
  24257. }
  24258. // Two threads must never parse WebSocket frames from the same stream.
  24259. // close() used to read the peer's Close reply with its own frame read, so it
  24260. // raced a reader thread that was in the middle of a payload: the payload loop
  24261. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24262. // so bytes taken by close() were replaced with bytes from further along the
  24263. // stream. The message kept its length and silently changed content.
  24264. //
  24265. // The raw peer below sends a frame header plus part of the payload, waits for
  24266. // the handler to call close(), and only then sends the rest. Whichever thread
  24267. // would win the race for those bytes, the message must arrive intact, because
  24268. // close() must not touch the stream while read() owns it.
  24269. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24270. #ifndef _WIN32
  24271. signal(SIGPIPE, SIG_IGN);
  24272. #endif
  24273. const size_t payload_len = 120; // fits the 7-bit length field
  24274. const size_t prefix_len = 8;
  24275. const int attempts = 8;
  24276. std::string expected(payload_len, '\0');
  24277. for (size_t i = 0; i < payload_len; i++) {
  24278. expected[i] = static_cast<char>('a' + i % 26);
  24279. }
  24280. std::atomic<bool> peer_stalled{false};
  24281. std::atomic<bool> handler_done{false};
  24282. std::mutex received_mutex;
  24283. std::vector<std::string> received;
  24284. // Bound every wait, so a regression fails the test instead of hanging the
  24285. // suite.
  24286. auto wait_for = [](const std::atomic<bool> &flag) {
  24287. for (int i = 0; i < 500 && !flag; i++) {
  24288. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24289. }
  24290. };
  24291. Server svr;
  24292. svr.set_websocket_ping_interval(0);
  24293. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24294. std::thread reader([&]() {
  24295. std::string msg;
  24296. while (ws.read(msg)) {
  24297. std::lock_guard<std::mutex> guard(received_mutex);
  24298. received.push_back(msg);
  24299. }
  24300. });
  24301. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24302. // inside read_websocket_frame() when close() runs.
  24303. wait_for(peer_stalled);
  24304. ws.close();
  24305. reader.join();
  24306. handler_done = true;
  24307. });
  24308. auto port = svr.bind_to_any_port("127.0.0.1");
  24309. std::thread t([&]() { svr.listen_after_bind(); });
  24310. auto se = detail::scope_exit([&] {
  24311. svr.stop();
  24312. t.join();
  24313. });
  24314. svr.wait_until_ready();
  24315. auto send_bytes = [](socket_t s, const std::string &data) {
  24316. #ifdef _WIN32
  24317. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24318. #else
  24319. auto n = ::send(s, data.data(), data.size(), 0);
  24320. #endif
  24321. return n == static_cast<decltype(n)>(data.size());
  24322. };
  24323. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24324. // Every length used here fits the 7-bit length field.
  24325. auto masked_header = [](uint8_t first_byte, size_t len) {
  24326. std::string h;
  24327. h += static_cast<char>(first_byte);
  24328. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24329. h.append(4, '\0'); // mask key
  24330. return h;
  24331. };
  24332. for (int attempt = 0; attempt < attempts; attempt++) {
  24333. peer_stalled = false;
  24334. handler_done = false;
  24335. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24336. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24337. auto se_sock = detail::scope_exit([&] {
  24338. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24339. });
  24340. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24341. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24342. sockaddr_in addr{};
  24343. addr.sin_family = AF_INET;
  24344. addr.sin_port = htons(static_cast<uint16_t>(port));
  24345. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24346. ASSERT_EQ(
  24347. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24348. << "attempt " << attempt;
  24349. ASSERT_TRUE(send_bytes(sock,
  24350. "GET /ws HTTP/1.1\r\n"
  24351. "Host: 127.0.0.1\r\n"
  24352. "Upgrade: websocket\r\n"
  24353. "Connection: Upgrade\r\n"
  24354. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24355. "Sec-WebSocket-Version: 13\r\n"
  24356. "\r\n"))
  24357. << "attempt " << attempt;
  24358. std::string response;
  24359. while (response.find("\r\n\r\n") == std::string::npos) {
  24360. char buf[512];
  24361. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24362. if (n <= 0) { break; }
  24363. response.append(buf, static_cast<size_t>(n));
  24364. }
  24365. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24366. << "attempt " << attempt;
  24367. // Send the header of a Binary message but only the first prefix_len bytes
  24368. // of its payload, leaving the reader thread stalled inside the payload.
  24369. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24370. expected.substr(0, prefix_len)))
  24371. << "attempt " << attempt;
  24372. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24373. peer_stalled = true;
  24374. // Let close() send its Close frame and park in its own read before the
  24375. // rest of the payload arrives, so both threads are waiting for it.
  24376. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24377. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24378. close_frame += static_cast<char>(0x03); // status 1000
  24379. close_frame += static_cast<char>(0xE8);
  24380. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24381. << "attempt " << attempt;
  24382. // Closing the peer releases the reader thread even on the buggy path,
  24383. // where it waits for bytes another thread already consumed.
  24384. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24385. detail::close_socket(sock);
  24386. sock = INVALID_SOCKET;
  24387. wait_for(handler_done);
  24388. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24389. }
  24390. std::lock_guard<std::mutex> guard(received_mutex);
  24391. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24392. << "a message in flight when close() ran was dropped";
  24393. for (size_t i = 0; i < received.size(); i++) {
  24394. EXPECT_EQ(expected, received[i]) << "message " << i;
  24395. }
  24396. }
  24397. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24398. // returning the socket, or INVALID_SOCKET.
  24399. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24400. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24401. if (sock == INVALID_SOCKET) { return sock; }
  24402. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24403. sockaddr_in addr{};
  24404. addr.sin_family = AF_INET;
  24405. addr.sin_port = htons(static_cast<uint16_t>(port));
  24406. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24407. std::string req = "GET " + path +
  24408. " HTTP/1.1\r\n"
  24409. "Host: 127.0.0.1\r\n"
  24410. "Upgrade: websocket\r\n"
  24411. "Connection: Upgrade\r\n"
  24412. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24413. "Sec-WebSocket-Version: 13\r\n"
  24414. "\r\n";
  24415. std::string res;
  24416. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24417. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24418. static_cast<ssize_t>(req.size())) {
  24419. char c;
  24420. while (res.find("\r\n\r\n") == std::string::npos &&
  24421. ::recv(sock, &c, 1, 0) == 1) {
  24422. res += c;
  24423. }
  24424. }
  24425. if (res.find(" 101 ") == std::string::npos) {
  24426. detail::close_socket(sock);
  24427. return INVALID_SOCKET;
  24428. }
  24429. return sock;
  24430. }
  24431. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24432. // The payload must fit the 7-bit length field.
  24433. static std::string masked_frame(uint8_t first_byte,
  24434. const std::string &payload) {
  24435. std::string f;
  24436. f += static_cast<char>(first_byte);
  24437. f += static_cast<char>(0x80 | payload.size());
  24438. f.append(4, '\0');
  24439. return f + payload;
  24440. }
  24441. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24442. std::atomic<bool> done{false};
  24443. std::string received;
  24444. Server svr;
  24445. svr.set_websocket_ping_interval(0);
  24446. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24447. std::string msg;
  24448. if (ws.read(msg) == ws::Binary) { received = msg; }
  24449. done = true;
  24450. });
  24451. auto port = svr.bind_to_any_port("127.0.0.1");
  24452. std::thread t([&]() { svr.listen_after_bind(); });
  24453. auto se = detail::scope_exit([&] {
  24454. svr.stop();
  24455. t.join();
  24456. });
  24457. svr.wait_until_ready();
  24458. auto sock = connect_raw_websocket(port, "/ws");
  24459. ASSERT_NE(INVALID_SOCKET, sock);
  24460. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24461. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24462. masked_frame(0x89, "p") + // FIN + Ping
  24463. masked_frame(0x80, "lo"); // FIN + Continuation
  24464. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24465. for (int i = 0; i < 500 && !done; i++) {
  24466. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24467. }
  24468. ASSERT_TRUE(done);
  24469. EXPECT_EQ("Hello", received);
  24470. // The Ping between the fragments is answered with a Pong.
  24471. char pong[3];
  24472. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24473. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24474. }
  24475. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24476. Server svr;
  24477. svr.set_websocket_ping_interval(-1);
  24478. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24479. std::string msg;
  24480. while (ws.read(msg)) {}
  24481. });
  24482. auto port = svr.bind_to_any_port("127.0.0.1");
  24483. std::thread t([&]() { svr.listen_after_bind(); });
  24484. auto se = detail::scope_exit([&] {
  24485. svr.stop();
  24486. t.join();
  24487. });
  24488. svr.wait_until_ready();
  24489. auto sock = connect_raw_websocket(port, "/ws");
  24490. ASSERT_NE(INVALID_SOCKET, sock);
  24491. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24492. // Nothing comes while the client stays quiet.
  24493. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24494. char c;
  24495. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24496. }
  24497. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24498. // and that has to end a read() already waiting on the peer, on every platform.
  24499. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24500. // The peer sends no pings, and its handler never calls read(), which is
  24501. // where pongs are written.
  24502. std::mutex mutex;
  24503. std::condition_variable cv;
  24504. auto release = false;
  24505. svr.set_websocket_ping_interval(0);
  24506. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24507. std::unique_lock<std::mutex> lock(mutex);
  24508. cv.wait(lock, [&] { return release; });
  24509. });
  24510. auto port = svr.bind_to_any_port(HOST);
  24511. std::thread t([&]() { svr.listen_after_bind(); });
  24512. auto se = detail::scope_exit([&] {
  24513. {
  24514. std::lock_guard<std::mutex> lock(mutex);
  24515. release = true;
  24516. }
  24517. cv.notify_all();
  24518. svr.stop();
  24519. t.join();
  24520. });
  24521. svr.wait_until_ready();
  24522. ws::WebSocketClient client(std::string(scheme) +
  24523. "://localhost:" + std::to_string(port) + "/ws");
  24524. #ifdef CPPHTTPLIB_SSL_ENABLED
  24525. client.enable_server_certificate_verification(false);
  24526. #endif
  24527. // A ping a second, given up on after two go unanswered: about 3s
  24528. client.set_websocket_ping_interval(1);
  24529. client.set_websocket_max_missed_pongs(2);
  24530. // Well past that, so that a read the timeout ends instead stands out
  24531. client.set_read_timeout(10);
  24532. ASSERT_TRUE(client.connect());
  24533. auto start = std::chrono::steady_clock::now();
  24534. std::string msg;
  24535. EXPECT_EQ(ws::Fail, client.read(msg));
  24536. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24537. std::chrono::steady_clock::now() - start)
  24538. .count(),
  24539. 6000);
  24540. EXPECT_FALSE(client.is_open());
  24541. }
  24542. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24543. Server svr;
  24544. check_pong_timeout_ends_read(svr, "ws");
  24545. }
  24546. #ifdef CPPHTTPLIB_SSL_ENABLED
  24547. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24549. ASSERT_TRUE(svr.is_valid());
  24550. check_pong_timeout_ends_read(svr, "wss");
  24551. }
  24552. #endif
  24553. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24554. Server svr;
  24555. svr.set_websocket_ping_interval(0);
  24556. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24557. std::string msg;
  24558. while (ws.read(msg)) {}
  24559. });
  24560. auto port = svr.bind_to_any_port("127.0.0.1");
  24561. std::thread t([&]() { svr.listen_after_bind(); });
  24562. auto se = detail::scope_exit([&] {
  24563. svr.stop();
  24564. t.join();
  24565. });
  24566. svr.wait_until_ready();
  24567. // Each Close payload and the reply it should get: an echo when valid, 1002
  24568. // otherwise.
  24569. std::vector<std::pair<std::string, std::string>> cases = {
  24570. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24571. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24572. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24573. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24574. };
  24575. // Also between the fragments of a message.
  24576. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24577. for (const auto &c : cases) {
  24578. auto sock = connect_raw_websocket(port, "/ws");
  24579. ASSERT_NE(INVALID_SOCKET, sock);
  24580. auto frames = prefix + masked_frame(0x88, c.first);
  24581. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24582. std::string reply;
  24583. char buf[256];
  24584. while (reply.size() < 2 + c.second.size()) {
  24585. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24586. if (n <= 0) { break; }
  24587. reply.append(buf, static_cast<size_t>(n));
  24588. }
  24589. detail::close_socket(sock);
  24590. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24591. c.second,
  24592. reply);
  24593. }
  24594. }
  24595. }
  24596. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24597. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24598. protected:
  24599. void SetUp() override {
  24600. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24601. SERVER_PRIVATE_KEY_FILE);
  24602. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24603. std::string msg;
  24604. ws::ReadResult ret;
  24605. while ((ret = ws.read(msg))) {
  24606. if (ret == ws::Binary) {
  24607. ws.send(msg.data(), msg.size());
  24608. } else {
  24609. ws.send(msg);
  24610. }
  24611. }
  24612. });
  24613. port_ = server_->bind_to_any_port(HOST);
  24614. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24615. server_->wait_until_ready();
  24616. }
  24617. void TearDown() override {
  24618. server_->stop();
  24619. if (server_thread_.joinable()) { server_thread_.join(); }
  24620. }
  24621. std::unique_ptr<SSLServer> server_;
  24622. std::thread server_thread_;
  24623. int port_ = 0;
  24624. };
  24625. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24626. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24627. {
  24628. ws::WebSocketClient client(url);
  24629. client.enable_server_certificate_verification(false);
  24630. auto calls = 0;
  24631. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24632. calls++;
  24633. return false;
  24634. });
  24635. EXPECT_FALSE(client.connect());
  24636. EXPECT_GT(calls, 0);
  24637. }
  24638. {
  24639. ws::WebSocketClient client(url);
  24640. client.enable_server_certificate_verification(false);
  24641. client.set_session_verifier([](tls::session_t) {
  24642. return SSLVerifierResponse::CertificateRejected;
  24643. });
  24644. EXPECT_FALSE(client.connect());
  24645. }
  24646. {
  24647. ws::WebSocketClient client(url);
  24648. client.enable_server_certificate_verification(false);
  24649. client.set_session_verifier([](tls::session_t) {
  24650. return SSLVerifierResponse::CertificateAccepted;
  24651. });
  24652. EXPECT_TRUE(client.connect());
  24653. }
  24654. }
  24655. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24656. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24657. "/ws-echo");
  24658. client.enable_server_certificate_verification(false);
  24659. ASSERT_TRUE(client.connect());
  24660. ASSERT_TRUE(client.is_open());
  24661. ASSERT_TRUE(client.send("Hello WSS"));
  24662. std::string msg;
  24663. EXPECT_EQ(ws::Text, client.read(msg));
  24664. EXPECT_EQ("Hello WSS", msg);
  24665. client.close();
  24666. }
  24667. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24668. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24669. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24670. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24671. // client (without calling close() first) is the only path that runs
  24672. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24673. // bug exactly.
  24674. //
  24675. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24676. // when linked against an instrumented libssl; run under Valgrind to catch it
  24677. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24678. // suite (the freed session otherwise stalls on the close handshake) — this test
  24679. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24680. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24681. {
  24682. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24683. "/ws-echo");
  24684. client.enable_server_certificate_verification(false);
  24685. client.set_read_timeout(2, 0);
  24686. client.set_write_timeout(2, 0);
  24687. ASSERT_TRUE(client.connect());
  24688. ASSERT_TRUE(client.is_open());
  24689. ASSERT_TRUE(client.send("still open"));
  24690. // Intentionally do NOT call client.close(): leaving scope runs
  24691. // shutdown_and_close() with the WebSocket still open, which must send the
  24692. // close frame while the TLS session is still alive.
  24693. }
  24694. }
  24695. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24696. // shutdown_and_close() at the start of connect(), reproducing the same
  24697. // use-after-free within the test body rather than at scope exit. The second
  24698. // connect must succeed and echo, proving the close handshake ran over a live
  24699. // session. See the note above about memory-tool requirements.
  24700. TEST_F(WebSocketSSLIntegrationTest,
  24701. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24702. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24703. "/ws-echo");
  24704. client.enable_server_certificate_verification(false);
  24705. client.set_read_timeout(2, 0);
  24706. client.set_write_timeout(2, 0);
  24707. ASSERT_TRUE(client.connect());
  24708. ASSERT_TRUE(client.is_open());
  24709. ASSERT_TRUE(client.send("still open"));
  24710. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24711. // the still-open connection, which must not touch a freed TLS session.
  24712. ASSERT_TRUE(client.connect());
  24713. ASSERT_TRUE(client.is_open());
  24714. ASSERT_TRUE(client.send("after reconnect"));
  24715. std::string msg;
  24716. EXPECT_EQ(ws::Text, client.read(msg));
  24717. EXPECT_EQ("after reconnect", msg);
  24718. client.close();
  24719. }
  24720. #endif
  24721. #ifdef CPPHTTPLIB_SSL_ENABLED
  24722. class WebSocketSSLCATest : public ::testing::Test {
  24723. protected:
  24724. void SetUp() override {
  24725. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24726. SERVER_PRIVATE_KEY_FILE);
  24727. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24728. std::string msg;
  24729. while (ws.read(msg)) {
  24730. ws.send(msg);
  24731. }
  24732. });
  24733. port_ = server_->bind_to_any_port("127.0.0.1");
  24734. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24735. server_->wait_until_ready();
  24736. }
  24737. void TearDown() override {
  24738. server_->stop();
  24739. if (server_thread_.joinable()) { server_thread_.join(); }
  24740. }
  24741. std::string url() const {
  24742. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24743. }
  24744. std::unique_ptr<SSLServer> server_;
  24745. std::thread server_thread_;
  24746. int port_ = 0;
  24747. };
  24748. // A custom CA loaded as PEM verifies the server with full certificate
  24749. // verification enabled
  24750. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24751. ws::WebSocketClient client(url());
  24752. std::string cert;
  24753. read_file(SERVER_CERT2_FILE, cert);
  24754. client.load_ca_cert_store(cert.c_str(), cert.size());
  24755. ASSERT_TRUE(client.connect());
  24756. ASSERT_TRUE(client.send("hello"));
  24757. std::string msg;
  24758. EXPECT_EQ(ws::Text, client.read(msg));
  24759. EXPECT_EQ("hello", msg);
  24760. client.close();
  24761. }
  24762. // A custom CA that does not cover the server must fail verification (the
  24763. // custom CA is exclusive; system certs are not loaded alongside it)
  24764. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24765. ws::WebSocketClient client(url());
  24766. std::string cert;
  24767. read_file(CLIENT_CA_CERT_FILE, cert);
  24768. client.load_ca_cert_store(cert.c_str(), cert.size());
  24769. auto res = client.connect();
  24770. ASSERT_FALSE(res);
  24771. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24772. EXPECT_EQ(-1, res.status());
  24773. EXPECT_NE(0u, res.ssl_backend_error());
  24774. }
  24775. // The same CA as a file path rather than PEM in memory
  24776. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24777. ws::WebSocketClient client(url());
  24778. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24779. ASSERT_TRUE(client.connect());
  24780. ASSERT_TRUE(client.send("hello"));
  24781. std::string msg;
  24782. EXPECT_EQ(ws::Text, client.read(msg));
  24783. EXPECT_EQ("hello", msg);
  24784. client.close();
  24785. }
  24786. // ...and a CA file that does not cover the server still fails, so it is the
  24787. // path above that decides the outcome
  24788. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24789. ws::WebSocketClient client(url());
  24790. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24791. ASSERT_FALSE(client.connect());
  24792. }
  24793. // Regression test: reconnecting with a native custom CA store used to reuse
  24794. // a store handle the previous TLS context had already freed (use-after-free
  24795. // under the OpenSSL backend). The context now lives as long as the client.
  24796. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24797. ws::WebSocketClient client(url());
  24798. std::string cert;
  24799. read_file(SERVER_CERT2_FILE, cert);
  24800. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24801. ASSERT_TRUE(client.connect());
  24802. client.close();
  24803. ASSERT_TRUE(client.connect());
  24804. ASSERT_TRUE(client.send("again"));
  24805. std::string msg;
  24806. EXPECT_EQ(ws::Text, client.read(msg));
  24807. EXPECT_EQ("again", msg);
  24808. client.close();
  24809. }
  24810. // Regression test: a certificate with a trusted chain but no identity match
  24811. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24812. // verification entirely for IP hosts, so this connection succeeded there.
  24813. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24814. // chain verification while the identity check must still fail.
  24815. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24817. ASSERT_TRUE(svr.is_valid());
  24818. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24819. std::string msg;
  24820. while (ws.read(msg)) {
  24821. ws.send(msg);
  24822. }
  24823. });
  24824. auto port = svr.bind_to_any_port("127.0.0.1");
  24825. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24826. auto se = detail::scope_exit([&] {
  24827. svr.stop();
  24828. t.join();
  24829. });
  24830. svr.wait_until_ready();
  24831. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24832. "/echo");
  24833. std::string cert;
  24834. read_file(SERVER_CERT_FILE, cert);
  24835. client.load_ca_cert_store(cert.c_str(), cert.size());
  24836. ASSERT_FALSE(client.connect());
  24837. }
  24838. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24839. // SNI, so nothing binds the host name to the TLS session. These bind the
  24840. // server to "localhost" instead, the only shape that exercises the SNI and
  24841. // hostname-verification path with certificate verification left enabled.
  24842. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24843. protected:
  24844. void Start(const char *cert_file) {
  24845. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24846. SERVER_PRIVATE_KEY_FILE);
  24847. ASSERT_TRUE(server_->is_valid());
  24848. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24849. std::string msg;
  24850. while (ws.read(msg)) {
  24851. ws.send(msg);
  24852. }
  24853. });
  24854. port_ = server_->bind_to_any_port("localhost");
  24855. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24856. server_->wait_until_ready();
  24857. }
  24858. void TearDown() override {
  24859. if (server_) { server_->stop(); }
  24860. if (server_thread_.joinable()) { server_thread_.join(); }
  24861. }
  24862. std::string url() const {
  24863. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24864. }
  24865. std::unique_ptr<SSLServer> server_;
  24866. std::thread server_thread_;
  24867. int port_ = 0;
  24868. };
  24869. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24870. // out and the connection is usable
  24871. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24872. Start(SERVER_CERT2_FILE);
  24873. ws::WebSocketClient client(url());
  24874. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24875. ASSERT_TRUE(client.connect());
  24876. ASSERT_TRUE(client.send("hello"));
  24877. std::string msg;
  24878. EXPECT_EQ(ws::Text, client.read(msg));
  24879. EXPECT_EQ("hello", msg);
  24880. client.close();
  24881. }
  24882. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24883. // while the identity check must still reject "localhost"
  24884. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24885. Start(SERVER_CERT_FILE);
  24886. ws::WebSocketClient client(url());
  24887. client.set_ca_cert_path(SERVER_CERT_FILE);
  24888. auto res = client.connect();
  24889. ASSERT_FALSE(res);
  24890. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24891. EXPECT_EQ(-1, res.status());
  24892. }
  24893. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24894. // disabled: the chain is still checked, only the identity check is skipped
  24895. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24896. Start(SERVER_CERT_FILE);
  24897. ws::WebSocketClient client(url());
  24898. client.set_ca_cert_path(SERVER_CERT_FILE);
  24899. client.enable_server_hostname_verification(false);
  24900. ASSERT_TRUE(client.connect());
  24901. ASSERT_TRUE(client.send("hello"));
  24902. std::string msg;
  24903. EXPECT_EQ(ws::Text, client.read(msg));
  24904. EXPECT_EQ("hello", msg);
  24905. client.close();
  24906. }
  24907. // A CA that did not sign the server certificate fails the chain, even though
  24908. // the name would match
  24909. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24910. Start(SERVER_CERT2_FILE);
  24911. ws::WebSocketClient client(url());
  24912. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24913. ASSERT_FALSE(client.connect());
  24914. }
  24915. // With verification disabled, neither the chain nor the name is checked
  24916. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24917. Start(SERVER_CERT_FILE);
  24918. ws::WebSocketClient client(url());
  24919. client.enable_server_certificate_verification(false);
  24920. ASSERT_TRUE(client.connect());
  24921. ASSERT_TRUE(client.send("hello"));
  24922. std::string msg;
  24923. EXPECT_EQ(ws::Text, client.read(msg));
  24924. EXPECT_EQ("hello", msg);
  24925. client.close();
  24926. }
  24927. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24928. protected:
  24929. void SetUp() override {
  24930. server_ = httplib::detail::make_unique<SSLServer>(
  24931. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24932. ASSERT_TRUE(server_->is_valid());
  24933. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24934. std::string msg;
  24935. while (ws.read(msg)) {
  24936. ws.send(msg);
  24937. }
  24938. });
  24939. port_ = server_->bind_to_any_port("localhost");
  24940. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24941. server_->wait_until_ready();
  24942. }
  24943. void TearDown() override {
  24944. server_->stop();
  24945. if (server_thread_.joinable()) { server_thread_.join(); }
  24946. }
  24947. std::string url() const {
  24948. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24949. }
  24950. void ConnectWithClientCert(const std::string &client_cert_file,
  24951. const std::string &client_private_key_file,
  24952. const char *private_key_password) {
  24953. std::string cert_pem, key_pem;
  24954. read_file(client_cert_file, cert_pem);
  24955. read_file(client_private_key_file, key_pem);
  24956. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24957. key_pem.c_str(), key_pem.size(),
  24958. private_key_password};
  24959. ConnectWithPem(pem);
  24960. }
  24961. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24962. ws::WebSocketClient client(url(), pem);
  24963. ASSERT_TRUE(client.is_valid());
  24964. client.enable_server_certificate_verification(false);
  24965. ASSERT_TRUE(client.connect());
  24966. ASSERT_TRUE(client.send("hello"));
  24967. std::string msg;
  24968. EXPECT_EQ(ws::Text, client.read(msg));
  24969. EXPECT_EQ("hello", msg);
  24970. client.close();
  24971. }
  24972. std::unique_ptr<SSLServer> server_;
  24973. std::thread server_thread_;
  24974. int port_ = 0;
  24975. };
  24976. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24977. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24978. }
  24979. // Control for the tests above: the fixture's server really does require a
  24980. // client certificate, so it is the PEM the constructor installed that decides
  24981. // the outcome.
  24982. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24983. ws::WebSocketClient client(url());
  24984. ASSERT_TRUE(client.is_valid());
  24985. client.enable_server_certificate_verification(false);
  24986. EXPECT_FALSE(client.connect());
  24987. }
  24988. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24989. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24990. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24991. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24992. }
  24993. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24994. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24995. std::string cert_pem, key_pem;
  24996. read_file(CLIENT_CERT_FILE, cert_pem);
  24997. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24998. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24999. std::vector<char> key(key_pem.begin(), key_pem.end());
  25000. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25001. key.size(), nullptr};
  25002. ConnectWithPem(pem);
  25003. }
  25004. #endif
  25005. #if !defined(_WIN32)
  25006. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25007. auto secret_dir = std::string("./symlink_test_secret");
  25008. auto served_dir = std::string("./symlink_test_served");
  25009. auto secret_file = secret_dir + "/secret.txt";
  25010. auto symlink_path = served_dir + "/escape";
  25011. // Setup: create directories and files
  25012. mkdir(secret_dir.c_str(), 0755);
  25013. mkdir(served_dir.c_str(), 0755);
  25014. {
  25015. std::ofstream ofs(secret_file);
  25016. ofs << "SECRET_DATA";
  25017. }
  25018. // Create symlink using absolute path so it resolves correctly
  25019. #ifdef PATH_MAX
  25020. char abs_secret[PATH_MAX];
  25021. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25022. #else
  25023. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25024. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25025. ASSERT_NE(nullptr, abs_secret);
  25026. #endif
  25027. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25028. auto se = detail::scope_exit([&] {
  25029. unlink(symlink_path.c_str());
  25030. unlink(secret_file.c_str());
  25031. rmdir(served_dir.c_str());
  25032. rmdir(secret_dir.c_str());
  25033. });
  25034. Server svr;
  25035. svr.set_mount_point("/", served_dir);
  25036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25037. auto se2 = detail::scope_exit([&] {
  25038. svr.stop();
  25039. listen_thread.join();
  25040. });
  25041. svr.wait_until_ready();
  25042. Client cli("localhost", PORT);
  25043. // Symlink pointing outside base dir should be blocked
  25044. auto res = cli.Get("/escape/secret.txt");
  25045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25046. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25047. }
  25048. #endif
  25049. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25050. // "GET /smuggled" request), reads the first response, and only then sends the
  25051. // embedded request as the body. Returns how many times /smuggled ran.
  25052. //
  25053. // The body is sent AFTER receiving the first response (as in the original
  25054. // PoC) so that the stream_line_reader cannot buffer it together with the
  25055. // headers of the first request.
  25056. static int count_smuggled_requests(const std::string &outer_head,
  25057. std::string &first_response) {
  25058. Server svr;
  25059. svr.set_mount_point("/", "./www");
  25060. std::atomic<int> smuggled_count(0);
  25061. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25062. smuggled_count++;
  25063. res.set_content("oops", "text/plain");
  25064. });
  25065. svr.Post("/post", [&](const Request &req, Response &res) {
  25066. res.set_content(req.body, "text/plain");
  25067. });
  25068. auto port = svr.bind_to_any_port("localhost");
  25069. thread t = thread([&] { svr.listen_after_bind(); });
  25070. auto se = detail::scope_exit([&] {
  25071. svr.stop();
  25072. t.join();
  25073. });
  25074. svr.wait_until_ready();
  25075. auto error = Error::Success;
  25076. auto sock = detail::create_client_socket(
  25077. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25078. /*connection_timeout_sec=*/2, 0,
  25079. /*read_timeout_sec=*/2, 0,
  25080. /*write_timeout_sec=*/2, 0, std::string(), error);
  25081. EXPECT_NE(INVALID_SOCKET, sock);
  25082. if (sock == INVALID_SOCKET) { return -1; }
  25083. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25084. // The "smuggled" request will be sent as the body of the outer request
  25085. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25086. "Host: localhost\r\n"
  25087. "Connection: close\r\n"
  25088. "\r\n";
  25089. auto head = outer_head;
  25090. auto len = std::to_string(smuggled.size());
  25091. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25092. pos = head.find("{len}", pos + len.size())) {
  25093. head.replace(pos, 5, len);
  25094. }
  25095. // Step 1: Send only the outer request headers (no body yet)
  25096. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25097. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25098. // Step 2: Read the first response
  25099. char buf[4096];
  25100. for (;;) {
  25101. auto n = recv(sock, buf, sizeof(buf), 0);
  25102. if (n <= 0) break;
  25103. first_response.append(buf, static_cast<size_t>(n));
  25104. // Stop once we have a complete response (headers + body)
  25105. auto hdr_end = first_response.find("\r\n\r\n");
  25106. if (hdr_end != std::string::npos) {
  25107. // Check for Content-Length to know when the body is complete
  25108. auto cl_pos = first_response.find("Content-Length:");
  25109. if (cl_pos != std::string::npos) {
  25110. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25111. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25112. auto cl = std::stoul(
  25113. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25114. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25115. } else {
  25116. break; // No Content-Length, assume headers-only response
  25117. }
  25118. }
  25119. }
  25120. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25121. // vulnerable server the keep-alive loop reads this as a second request. The
  25122. // server may already have closed the connection, so the result is ignored.
  25123. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25124. // Half-close so that a server which drained the body sees EOF and closes,
  25125. // instead of the read below waiting for the read timeout.
  25126. #ifdef _WIN32
  25127. ::shutdown(sock, SD_SEND);
  25128. #else
  25129. ::shutdown(sock, SHUT_WR);
  25130. #endif
  25131. // Step 4: Read until the server closes the connection
  25132. for (;;) {
  25133. auto n = recv(sock, buf, sizeof(buf), 0);
  25134. if (n <= 0) break;
  25135. }
  25136. return smuggled_count.load();
  25137. }
  25138. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25139. // A GET request with Content-Length to a static file handler must have its
  25140. // body drained before the keep-alive connection is reused. Otherwise the
  25141. // unread body bytes are interpreted as the next HTTP request.
  25142. std::string first_response;
  25143. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25144. "Host: localhost\r\n"
  25145. "Content-Length: {len}\r\n"
  25146. "\r\n",
  25147. first_response));
  25148. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25149. }
  25150. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25151. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25152. // be answered with 400 and the connection closed. Treating it as "no body"
  25153. // leaves the body to be parsed as the next request.
  25154. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25155. const char *targets[] = {
  25156. "GET /file", // handler that never reads the body
  25157. "GET /not-found", // no handler matches (404)
  25158. "POST /post", // handler that reads the body
  25159. };
  25160. for (auto target : targets) {
  25161. for (auto value : values) {
  25162. std::string first_response;
  25163. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25164. " HTTP/1.1\r\n"
  25165. "Host: localhost\r\n"
  25166. "Content-Length: " +
  25167. value + "\r\n\r\n",
  25168. first_response))
  25169. << target << " with Content-Length: " << value;
  25170. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25171. << target << " with Content-Length: " << value;
  25172. }
  25173. }
  25174. }
  25175. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25176. // A 400 for an unparseable request line leaves the rest of the message
  25177. // unread, so the connection must be closed rather than reused.
  25178. std::string first_response;
  25179. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25180. "Host: localhost\r\n"
  25181. "Content-Length: {len}\r\n"
  25182. "\r\n",
  25183. first_response));
  25184. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25185. }
  25186. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25187. // Same as above for a header block that fails to parse.
  25188. std::string first_response;
  25189. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25190. "Host: localhost\r\n"
  25191. "Bad Header\r\n"
  25192. "Content-Length: {len}\r\n"
  25193. "\r\n",
  25194. first_response));
  25195. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25196. }
  25197. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25198. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25199. // server must not read another request on that connection, even when the
  25200. // request had no body to drain.
  25201. std::string first_response;
  25202. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25203. "Host: localhost\r\n"
  25204. "\r\n",
  25205. first_response));
  25206. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25207. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25208. }
  25209. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25210. // A content reader that stops early leaves the stream inside the body.
  25211. // Draining the whole Content-Length from there, or reading the body again,
  25212. // reads into the next request, and whatever follows is parsed as a request
  25213. // of its own.
  25214. Server svr;
  25215. std::atomic<int> smuggled_count(0);
  25216. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25217. svr.Post("/upload", [](const Request &req, Response &res,
  25218. const ContentReader &content_reader) {
  25219. // Stop at the last chunk, so the whole body has been read however it
  25220. // arrives.
  25221. auto length = req.get_header_value_u64("Content-Length");
  25222. size_t total = 0;
  25223. auto consumed = content_reader([&](const char *, size_t n) {
  25224. total += n;
  25225. return total < length;
  25226. });
  25227. EXPECT_FALSE(consumed);
  25228. if (req.has_param("retry")) {
  25229. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25230. }
  25231. // Replace the 400 the aborted read set, which would close the connection.
  25232. res.set_redirect("/done");
  25233. });
  25234. auto port = svr.bind_to_any_port(HOST);
  25235. thread t = thread([&] { svr.listen_after_bind(); });
  25236. auto se = detail::scope_exit([&] {
  25237. svr.stop();
  25238. t.join();
  25239. });
  25240. svr.wait_until_ready();
  25241. // A front end sees the second request as a POST whose body is the GET. The
  25242. // first body is as long as the POST's headers, so draining it again reads
  25243. // exactly those and leaves the GET to be parsed next.
  25244. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25245. "Host: localhost\r\n"
  25246. "\r\n";
  25247. std::string second_head = "POST /post HTTP/1.1\r\n"
  25248. "Host: localhost\r\n"
  25249. "Content-Length: " +
  25250. std::to_string(inner.size()) +
  25251. "\r\n"
  25252. "\r\n";
  25253. for (auto target : {"/upload", "/upload?retry"}) {
  25254. smuggled_count = 0;
  25255. std::string request = "POST " + std::string(target) +
  25256. " HTTP/1.1\r\n"
  25257. "Host: localhost\r\n"
  25258. "Content-Length: " +
  25259. std::to_string(second_head.size()) +
  25260. "\r\n"
  25261. "\r\n" +
  25262. std::string(second_head.size(), 'A') + second_head +
  25263. inner;
  25264. std::string response;
  25265. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25266. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25267. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25268. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25269. EXPECT_EQ(0, smuggled_count.load()) << target;
  25270. }
  25271. }
  25272. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25273. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25274. // must be rejected with 400 Bad Request.
  25275. Server svr;
  25276. svr.Post("/test", [&](const Request &, Response &res) {
  25277. res.set_content("ok", "text/plain");
  25278. });
  25279. thread t = thread([&] { svr.listen(HOST, PORT); });
  25280. auto se = detail::scope_exit([&] {
  25281. svr.stop();
  25282. t.join();
  25283. ASSERT_FALSE(svr.is_running());
  25284. });
  25285. svr.wait_until_ready();
  25286. // Exact "chunked"
  25287. {
  25288. auto req = "POST /test HTTP/1.1\r\n"
  25289. "Host: localhost\r\n"
  25290. "Content-Length: 5\r\n"
  25291. "Transfer-Encoding: chunked\r\n"
  25292. "Connection: close\r\n"
  25293. "\r\n"
  25294. "hello";
  25295. std::string response;
  25296. ASSERT_TRUE(send_request(1, req, &response));
  25297. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25298. response.substr(0, response.find("\r\n")));
  25299. }
  25300. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25301. {
  25302. auto req = "POST /test HTTP/1.1\r\n"
  25303. "Host: localhost\r\n"
  25304. "Content-Length: 5\r\n"
  25305. "Transfer-Encoding: gzip, chunked\r\n"
  25306. "Connection: close\r\n"
  25307. "\r\n"
  25308. "hello";
  25309. std::string response;
  25310. ASSERT_TRUE(send_request(1, req, &response));
  25311. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25312. response.substr(0, response.find("\r\n")));
  25313. }
  25314. }
  25315. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25316. Server svr;
  25317. svr.Post("/test", [&](const Request &, Response &res) {
  25318. res.set_content("ok", "text/plain");
  25319. });
  25320. thread t = thread([&] { svr.listen(HOST, PORT); });
  25321. auto se = detail::scope_exit([&] {
  25322. svr.stop();
  25323. t.join();
  25324. ASSERT_FALSE(svr.is_running());
  25325. });
  25326. svr.wait_until_ready();
  25327. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25328. // length cannot be determined, so the server must answer 400 and close
  25329. // rather than treat the request as bodyless and leave the body in the
  25330. // socket for the next request to pick up.
  25331. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25332. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25333. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25334. std::string response;
  25335. ASSERT_TRUE(send_request(1, req, &response));
  25336. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25337. response.substr(0, response.find("\r\n")))
  25338. << transfer_encoding;
  25339. }
  25340. // RFC 9110 5.3: the codings may also be split across several
  25341. // Transfer-Encoding lines, which combine in the order they were received.
  25342. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25343. // just like the single-line "chunked, gzip" above.
  25344. {
  25345. auto req = "POST /test HTTP/1.1\r\n"
  25346. "Host: localhost\r\n"
  25347. "Transfer-Encoding: chunked\r\n"
  25348. "Transfer-Encoding: gzip\r\n"
  25349. "\r\n"
  25350. "0\r\n\r\n";
  25351. std::string response;
  25352. ASSERT_TRUE(send_request(1, req, &response));
  25353. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25354. response.substr(0, response.find("\r\n")));
  25355. }
  25356. // A sequence ending in chunked stays valid.
  25357. auto req = "POST /test HTTP/1.1\r\n"
  25358. "Host: localhost\r\n"
  25359. "Transfer-Encoding: gzip, chunked\r\n"
  25360. "Connection: close\r\n"
  25361. "\r\n"
  25362. "0\r\n\r\n";
  25363. std::string response;
  25364. ASSERT_TRUE(send_request(1, req, &response));
  25365. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25366. // ...including when it is spread over several lines.
  25367. auto split_req = "POST /test HTTP/1.1\r\n"
  25368. "Host: localhost\r\n"
  25369. "Transfer-Encoding: gzip\r\n"
  25370. "Transfer-Encoding: chunked\r\n"
  25371. "Connection: close\r\n"
  25372. "\r\n"
  25373. "0\r\n\r\n";
  25374. std::string split_response;
  25375. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25376. EXPECT_EQ("HTTP/1.1 200 OK",
  25377. split_response.substr(0, split_response.find("\r\n")));
  25378. }
  25379. // Regression for issue #2450: a DELETE without Content-Length on a
  25380. // keep-alive connection must not let the post-response drain consume the
  25381. // next request's bytes.
  25382. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25383. Server svr;
  25384. std::atomic<int> delete_count(0);
  25385. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25386. delete_count++;
  25387. res.status = StatusCode::NoContent_204;
  25388. });
  25389. auto port = svr.bind_to_any_port(HOST);
  25390. thread t = thread([&] { svr.listen_after_bind(); });
  25391. auto se = detail::scope_exit([&] {
  25392. svr.stop();
  25393. t.join();
  25394. });
  25395. svr.wait_until_ready();
  25396. auto error = Error::Success;
  25397. auto sock = detail::create_client_socket(
  25398. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25399. /*connection_timeout_sec=*/2, 0,
  25400. /*read_timeout_sec=*/2, 0,
  25401. /*write_timeout_sec=*/2, 0, std::string(), error);
  25402. ASSERT_NE(INVALID_SOCKET, sock);
  25403. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25404. auto send_request_and_read_response = [&](const std::string &req,
  25405. std::string &out) -> bool {
  25406. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25407. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25408. char buf[4096];
  25409. for (;;) {
  25410. auto n = recv(sock, buf, sizeof(buf), 0);
  25411. if (n <= 0) { return !out.empty(); }
  25412. out.append(buf, static_cast<size_t>(n));
  25413. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25414. }
  25415. };
  25416. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25417. "Host: localhost\r\n"
  25418. "\r\n";
  25419. std::string resp1;
  25420. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25421. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25422. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25423. "Host: localhost\r\n"
  25424. "Connection: close\r\n"
  25425. "\r\n";
  25426. std::string resp2;
  25427. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25428. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25429. EXPECT_EQ(2, delete_count.load());
  25430. }
  25431. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25432. Server svr;
  25433. svr.Post("/ingest", [&](const Request &, Response &res,
  25434. const ContentReader &content_reader) {
  25435. auto consumed = content_reader([](const char *, size_t) { return false; });
  25436. EXPECT_FALSE(consumed);
  25437. res.status = StatusCode::Conflict_409;
  25438. res.set_header("Connection", "close");
  25439. });
  25440. auto port = svr.bind_to_any_port(HOST);
  25441. thread t = thread([&] { svr.listen_after_bind(); });
  25442. auto se = detail::scope_exit([&] {
  25443. svr.stop();
  25444. t.join();
  25445. });
  25446. svr.wait_until_ready();
  25447. auto error = Error::Success;
  25448. auto sock = detail::create_client_socket(
  25449. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25450. /*connection_timeout_sec=*/2, 0,
  25451. /*read_timeout_sec=*/1, 0,
  25452. /*write_timeout_sec=*/2, 0, std::string(), error);
  25453. ASSERT_NE(INVALID_SOCKET, sock);
  25454. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25455. std::string request = "POST /ingest HTTP/1.1\r\n"
  25456. "Host: localhost\r\n"
  25457. "Transfer-Encoding: chunked\r\n"
  25458. "\r\n"
  25459. "4\r\n"
  25460. "data\r\n";
  25461. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25462. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25463. std::string response;
  25464. ssize_t received = 0;
  25465. do {
  25466. char buf[4096];
  25467. received = recv(sock, buf, sizeof(buf), 0);
  25468. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25469. } while (received > 0);
  25470. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25471. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25472. EXPECT_EQ(0, received);
  25473. }
  25474. namespace no_proxy_test {
  25475. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25476. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25477. // calling listen().
  25478. class ScopedServer {
  25479. public:
  25480. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25481. ~ScopedServer() {
  25482. svr_.stop();
  25483. if (th_.joinable()) { th_.join(); }
  25484. }
  25485. Server &svr() { return svr_; }
  25486. int port() const { return port_; }
  25487. void listen() {
  25488. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25489. svr_.wait_until_ready();
  25490. }
  25491. private:
  25492. Server svr_;
  25493. std::thread th_;
  25494. int port_ = 0;
  25495. };
  25496. class ProxyAndTargetServers {
  25497. public:
  25498. ProxyAndTargetServers() {
  25499. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25500. proxy_hits_++;
  25501. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25502. res.set_content("via-proxy", "text/plain");
  25503. });
  25504. target_.Get(".*", [this](const Request &req, Response &res) {
  25505. target_hits_++;
  25506. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25507. res.set_content("direct", "text/plain");
  25508. });
  25509. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25510. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25511. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25512. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25513. proxy_mock_.wait_until_ready();
  25514. target_.wait_until_ready();
  25515. }
  25516. ~ProxyAndTargetServers() {
  25517. proxy_mock_.stop();
  25518. target_.stop();
  25519. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25520. if (target_thread_.joinable()) { target_thread_.join(); }
  25521. }
  25522. Server &proxy_mock() { return proxy_mock_; }
  25523. Server &target() { return target_; }
  25524. int proxy_port() const { return proxy_port_; }
  25525. int target_port() const { return target_port_; }
  25526. int proxy_hits() const { return proxy_hits_.load(); }
  25527. int target_hits() const { return target_hits_.load(); }
  25528. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25529. void reset_counters() {
  25530. proxy_hits_ = 0;
  25531. target_hits_ = 0;
  25532. last_had_proxy_authz_ = false;
  25533. }
  25534. private:
  25535. Server proxy_mock_;
  25536. Server target_;
  25537. std::thread proxy_thread_;
  25538. std::thread target_thread_;
  25539. int proxy_port_ = 0;
  25540. int target_port_ = 0;
  25541. std::atomic<int> proxy_hits_{0};
  25542. std::atomic<int> target_hits_{0};
  25543. std::atomic<bool> last_had_proxy_authz_{false};
  25544. };
  25545. inline std::unique_ptr<Client> make_client(const std::string &host,
  25546. ProxyAndTargetServers &s) {
  25547. auto cli = detail::make_unique<Client>(host, s.target_port());
  25548. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25549. cli->set_proxy("127.0.0.1", s.proxy_port());
  25550. return cli;
  25551. }
  25552. } // namespace no_proxy_test
  25553. using no_proxy_test::make_client;
  25554. using no_proxy_test::ProxyAndTargetServers;
  25555. // A stream request carries the credentials a buffered request does
  25556. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25557. no_proxy_test::ScopedServer origin;
  25558. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25559. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25560. });
  25561. origin.listen();
  25562. Client cli("127.0.0.1", origin.port());
  25563. cli.set_basic_auth("user", "pass");
  25564. auto handle = cli.open_stream("GET", "/x");
  25565. ASSERT_TRUE(handle.is_valid());
  25566. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25567. Client bearer("127.0.0.1", origin.port());
  25568. bearer.set_bearer_token_auth("tok");
  25569. auto handle2 = bearer.open_stream("GET", "/x");
  25570. ASSERT_TRUE(handle2.is_valid());
  25571. EXPECT_EQ("Bearer tok", read_all(handle2));
  25572. }
  25573. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25574. // takes its own credentials, as for a buffered request
  25575. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25576. std::string target, authz, proxy_authz;
  25577. no_proxy_test::ScopedServer proxy;
  25578. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25579. target = req.target;
  25580. authz = req.get_header_value("Authorization");
  25581. proxy_authz = req.get_header_value("Proxy-Authorization");
  25582. res.set_content("ok", "text/plain");
  25583. });
  25584. proxy.listen();
  25585. Client cli("origin.example", 8080);
  25586. cli.set_proxy("127.0.0.1", proxy.port());
  25587. cli.set_proxy_basic_auth("puser", "ppass");
  25588. cli.set_basic_auth("user", "pass");
  25589. auto handle = cli.open_stream("GET", "/x");
  25590. ASSERT_TRUE(handle.is_valid());
  25591. EXPECT_EQ("ok", read_all(handle));
  25592. EXPECT_EQ("http://origin.example:8080/x", target);
  25593. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25594. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25595. }
  25596. TEST(NoProxyTest, ExactHostnameBypasses) {
  25597. ProxyAndTargetServers s;
  25598. auto cli = make_client("example.com", s);
  25599. cli->set_no_proxy({"example.com"});
  25600. auto res = cli->Get("/");
  25601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25602. EXPECT_EQ(0, s.proxy_hits());
  25603. EXPECT_EQ(1, s.target_hits());
  25604. }
  25605. TEST(NoProxyTest, SubdomainBypasses) {
  25606. ProxyAndTargetServers s;
  25607. auto cli = make_client("foo.example.com", s);
  25608. cli->set_no_proxy({"example.com"});
  25609. auto res = cli->Get("/");
  25610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25611. EXPECT_EQ(0, s.proxy_hits());
  25612. EXPECT_EQ(1, s.target_hits());
  25613. }
  25614. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25615. // Regression guard: "evilexample.com" must not be considered a subdomain
  25616. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25617. // check would let traffic bypass the proxy and leak credentials direct
  25618. // to the attacker host.
  25619. ProxyAndTargetServers s;
  25620. auto cli = make_client("evilexample.com", s);
  25621. cli->set_no_proxy({"example.com"});
  25622. auto res = cli->Get("/");
  25623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25624. EXPECT_GE(s.proxy_hits(), 1);
  25625. EXPECT_EQ(0, s.target_hits());
  25626. }
  25627. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25628. ProxyAndTargetServers s;
  25629. auto cli = make_client("example.com.evil.com", s);
  25630. cli->set_no_proxy({"example.com"});
  25631. auto res = cli->Get("/");
  25632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25633. EXPECT_GE(s.proxy_hits(), 1);
  25634. EXPECT_EQ(0, s.target_hits());
  25635. }
  25636. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25637. ProxyAndTargetServers s;
  25638. auto cli = make_client("example.com", s);
  25639. cli->set_no_proxy({".example.com"});
  25640. auto res = cli->Get("/");
  25641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25642. EXPECT_EQ(0, s.proxy_hits());
  25643. EXPECT_EQ(1, s.target_hits());
  25644. }
  25645. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25646. ProxyAndTargetServers s;
  25647. auto cli = make_client("Example.COM", s);
  25648. cli->set_no_proxy({"EXAMPLE.com"});
  25649. auto res = cli->Get("/");
  25650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25651. EXPECT_EQ(0, s.proxy_hits());
  25652. EXPECT_EQ(1, s.target_hits());
  25653. }
  25654. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25655. ProxyAndTargetServers s;
  25656. auto cli = make_client("example.com.", s);
  25657. cli->set_no_proxy({"example.com"});
  25658. auto res = cli->Get("/");
  25659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25660. EXPECT_EQ(0, s.proxy_hits());
  25661. EXPECT_EQ(1, s.target_hits());
  25662. }
  25663. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25664. // Trailing dots must be normalized on BOTH sides — host and entry.
  25665. // An implementation that only strips the host-side trailing dot would
  25666. // fail to match host "example.com" against entry "example.com." because
  25667. // a literal substring search would compare 11 chars against 12.
  25668. ProxyAndTargetServers s;
  25669. auto cli = make_client("example.com", s);
  25670. cli->set_no_proxy({"example.com."});
  25671. auto res = cli->Get("/");
  25672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25673. EXPECT_EQ(0, s.proxy_hits());
  25674. EXPECT_EQ(1, s.target_hits());
  25675. }
  25676. TEST(NoProxyTest, WildcardBypassesEverything) {
  25677. ProxyAndTargetServers s;
  25678. auto cli = make_client("anything.invalid.test", s);
  25679. cli->set_no_proxy({"*"});
  25680. auto res = cli->Get("/");
  25681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25682. EXPECT_EQ(0, s.proxy_hits());
  25683. EXPECT_EQ(1, s.target_hits());
  25684. }
  25685. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25686. ProxyAndTargetServers s;
  25687. Client cli("127.0.0.1", s.target_port());
  25688. cli.set_proxy("127.0.0.1", s.proxy_port());
  25689. cli.set_no_proxy({"127.0.0.1"});
  25690. auto res = cli.Get("/");
  25691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25692. EXPECT_EQ(0, s.proxy_hits());
  25693. EXPECT_EQ(1, s.target_hits());
  25694. }
  25695. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25696. ProxyAndTargetServers s;
  25697. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25698. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25699. cli.set_proxy("127.0.0.1", s.proxy_port());
  25700. cli.set_no_proxy({"::1"});
  25701. auto res = cli.Get("/");
  25702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25703. EXPECT_EQ(0, s.proxy_hits());
  25704. EXPECT_EQ(1, s.target_hits());
  25705. }
  25706. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25707. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25708. // must still be recognized as IPv6 for CIDR matching. Implementations
  25709. // that detect IPv6 only when the host begins with '[' would parse the
  25710. // host as a hostname and miss the match.
  25711. ProxyAndTargetServers s;
  25712. Client cli("fe80::1", s.target_port());
  25713. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25714. cli.set_proxy("127.0.0.1", s.proxy_port());
  25715. cli.set_no_proxy({"fe80::/10"});
  25716. auto res = cli.Get("/");
  25717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25718. EXPECT_EQ(0, s.proxy_hits());
  25719. EXPECT_EQ(1, s.target_hits());
  25720. }
  25721. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25722. ProxyAndTargetServers s;
  25723. Client cli("::1", s.target_port());
  25724. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25725. cli.set_proxy("127.0.0.1", s.proxy_port());
  25726. cli.set_no_proxy({"[::1]"});
  25727. auto res = cli.Get("/");
  25728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25729. EXPECT_EQ(0, s.proxy_hits());
  25730. EXPECT_EQ(1, s.target_hits());
  25731. }
  25732. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25733. ProxyAndTargetServers s;
  25734. Client cli("fe80::1", s.target_port());
  25735. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25736. cli.set_proxy("127.0.0.1", s.proxy_port());
  25737. cli.set_no_proxy({"[fe80::]/10"});
  25738. auto res = cli.Get("/");
  25739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25740. EXPECT_EQ(0, s.proxy_hits());
  25741. EXPECT_EQ(1, s.target_hits());
  25742. }
  25743. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25744. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25745. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25746. // tricks via address-family conversion.
  25747. ProxyAndTargetServers s;
  25748. Client cli("::ffff:127.0.0.1", s.target_port());
  25749. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25750. cli.set_proxy("127.0.0.1", s.proxy_port());
  25751. cli.set_no_proxy({"127.0.0.1"});
  25752. auto res = cli.Get("/");
  25753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25754. EXPECT_GE(s.proxy_hits(), 1);
  25755. EXPECT_EQ(0, s.target_hits());
  25756. }
  25757. TEST(NoProxyTest, IPv4CidrMatch) {
  25758. ProxyAndTargetServers s;
  25759. Client cli("127.0.0.1", s.target_port());
  25760. cli.set_proxy("127.0.0.1", s.proxy_port());
  25761. cli.set_no_proxy({"127.0.0.0/8"});
  25762. auto res = cli.Get("/");
  25763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25764. EXPECT_EQ(0, s.proxy_hits());
  25765. EXPECT_EQ(1, s.target_hits());
  25766. }
  25767. TEST(NoProxyTest, IPv4CidrNonMatch) {
  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({"10.0.0.0/8"});
  25772. auto res = cli.Get("/");
  25773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25774. EXPECT_GE(s.proxy_hits(), 1);
  25775. EXPECT_EQ(0, s.target_hits());
  25776. }
  25777. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25778. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25779. // IPv4 target matches.
  25780. ProxyAndTargetServers s;
  25781. Client cli("127.0.0.1", s.target_port());
  25782. cli.set_proxy("127.0.0.1", s.proxy_port());
  25783. cli.set_no_proxy({"0.0.0.0/0"});
  25784. auto res = cli.Get("/");
  25785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25786. EXPECT_EQ(0, s.proxy_hits());
  25787. EXPECT_EQ(1, s.target_hits());
  25788. }
  25789. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25790. ProxyAndTargetServers s;
  25791. Client cli("127.0.0.1", s.target_port());
  25792. cli.set_proxy("127.0.0.1", s.proxy_port());
  25793. cli.set_no_proxy({"127.0.0.1"});
  25794. auto res = cli.Get("/");
  25795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25796. EXPECT_EQ(0, s.proxy_hits());
  25797. EXPECT_EQ(1, s.target_hits());
  25798. }
  25799. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25800. ProxyAndTargetServers s;
  25801. Client cli("127.0.0.1", s.target_port());
  25802. cli.set_proxy("127.0.0.1", s.proxy_port());
  25803. cli.set_no_proxy({"127.0.0.0/33"});
  25804. auto res = cli.Get("/");
  25805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25806. EXPECT_GE(s.proxy_hits(), 1);
  25807. EXPECT_EQ(0, s.target_hits());
  25808. }
  25809. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25810. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25811. ProxyAndTargetServers s;
  25812. Client cli("127.0.0.1", s.target_port());
  25813. cli.set_proxy("127.0.0.1", s.proxy_port());
  25814. cli.set_no_proxy({"127.0.0.1/"});
  25815. auto res = cli.Get("/");
  25816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25817. EXPECT_GE(s.proxy_hits(), 1);
  25818. EXPECT_EQ(0, s.target_hits());
  25819. }
  25820. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25821. ProxyAndTargetServers s;
  25822. auto cli = make_client("internal.corp", s);
  25823. cli->set_proxy_basic_auth("u", "p");
  25824. cli->set_no_proxy({"internal.corp"});
  25825. auto res = cli->Get("/");
  25826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25827. EXPECT_EQ(1, s.target_hits());
  25828. EXPECT_EQ(0, s.proxy_hits());
  25829. EXPECT_FALSE(s.last_had_proxy_authz())
  25830. << "Proxy-Authorization must not be sent direct to the target";
  25831. }
  25832. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25833. ProxyAndTargetServers s;
  25834. auto cli = make_client("public.example", s);
  25835. cli->set_proxy_basic_auth("u", "p");
  25836. cli->set_no_proxy({"internal.corp"}); // does not match
  25837. auto res = cli->Get("/");
  25838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25839. EXPECT_GE(s.proxy_hits(), 1);
  25840. EXPECT_TRUE(s.last_had_proxy_authz());
  25841. }
  25842. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25843. std::atomic<int> hits{0};
  25844. std::atomic<int> hits_with_authz{0};
  25845. no_proxy_test::ScopedServer proxy_mock;
  25846. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25847. hits++;
  25848. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25849. if (req.target.find("/redir") != std::string::npos) {
  25850. res.set_redirect("http://other.example/landed");
  25851. } else {
  25852. res.set_content("via-proxy", "text/plain");
  25853. }
  25854. });
  25855. proxy_mock.listen();
  25856. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25857. hits = 0;
  25858. hits_with_authz = 0;
  25859. Client cli("public.example", 80);
  25860. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25861. cli.set_proxy_basic_auth(c.first, c.second);
  25862. cli.set_follow_location(true);
  25863. // The redirect to another host goes through the proxy as well
  25864. auto res = cli.Get("/redir");
  25865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25866. EXPECT_EQ(2, hits.load());
  25867. EXPECT_EQ(2, hits_with_authz.load());
  25868. }
  25869. }
  25870. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25871. ProxyAndTargetServers s;
  25872. auto cli = make_client("anything.test", s);
  25873. auto res = cli->Get("/");
  25874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25875. EXPECT_GE(s.proxy_hits(), 1);
  25876. EXPECT_EQ(0, s.target_hits());
  25877. }
  25878. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25879. ProxyAndTargetServers s;
  25880. auto cli = make_client("example.com", s);
  25881. cli->set_no_proxy({"example.com:8080"});
  25882. auto res = cli->Get("/");
  25883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25884. EXPECT_GE(s.proxy_hits(), 1);
  25885. EXPECT_EQ(0, s.target_hits());
  25886. }
  25887. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25888. ProxyAndTargetServers s;
  25889. auto cli = make_client("anything.test", s);
  25890. cli->set_no_proxy({"", " ", "\t"});
  25891. auto res = cli->Get("/");
  25892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25893. EXPECT_GE(s.proxy_hits(), 1);
  25894. EXPECT_EQ(0, s.target_hits());
  25895. }
  25896. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25897. // An entry with leading/trailing whitespace must still match — env-style
  25898. // values are commonly pasted with stray spaces and an implementation
  25899. // that feeds the raw token directly to inet_pton would fail to match
  25900. // valid CIDRs because of the spaces.
  25901. ProxyAndTargetServers s;
  25902. Client cli("127.0.0.1", s.target_port());
  25903. cli.set_proxy("127.0.0.1", s.proxy_port());
  25904. cli.set_no_proxy({" 127.0.0.0/8 "});
  25905. auto res = cli.Get("/");
  25906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25907. EXPECT_EQ(0, s.proxy_hits());
  25908. EXPECT_EQ(1, s.target_hits());
  25909. }
  25910. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25911. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25912. // go direct and must NOT carry Proxy-Authorization.
  25913. std::atomic<int> proxy_hits{0};
  25914. std::atomic<int> target_hits{0};
  25915. std::atomic<bool> target_saw_authz{false};
  25916. no_proxy_test::ScopedServer proxy_mock, target;
  25917. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25918. proxy_hits++;
  25919. res.status = 302;
  25920. res.set_header("Location", "http://127.0.0.1:" +
  25921. std::to_string(target.port()) + "/landed");
  25922. });
  25923. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25924. target_hits++;
  25925. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25926. res.set_content("direct", "text/plain");
  25927. });
  25928. proxy_mock.listen();
  25929. target.listen();
  25930. Client cli("public.example", target.port());
  25931. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25932. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25933. cli.set_proxy_basic_auth("u", "p");
  25934. cli.set_no_proxy({"127.0.0.1"});
  25935. cli.set_follow_location(true);
  25936. auto res = cli.Get("/redir");
  25937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25938. EXPECT_GE(proxy_hits.load(), 1);
  25939. EXPECT_GE(target_hits.load(), 1);
  25940. EXPECT_FALSE(target_saw_authz.load());
  25941. }
  25942. #ifdef CPPHTTPLIB_SSL_ENABLED
  25943. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25944. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25945. // proxy creds would be sent to the (possibly hostile) origin.
  25946. std::atomic<int> target_hits{0};
  25947. std::atomic<bool> target_saw_proxy_authz{false};
  25948. no_proxy_test::ScopedServer target;
  25949. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25950. target_hits++;
  25951. if (req.has_header("Proxy-Authorization")) {
  25952. target_saw_proxy_authz = true;
  25953. }
  25954. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25955. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25956. "nonce=\"abc\", algorithm=MD5");
  25957. });
  25958. target.listen();
  25959. // The proxy address is set to the target's port: the bypass MUST kick in;
  25960. // if it doesn't, the test still routes "via proxy" to the same server and
  25961. // the Proxy-Authorization assertion below catches the leak.
  25962. Client cli("evil.example", target.port());
  25963. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25964. cli.set_proxy("127.0.0.1", target.port());
  25965. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25966. cli.set_no_proxy({"evil.example"});
  25967. auto res = cli.Get("/x");
  25968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25969. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25970. EXPECT_EQ(1, target_hits.load());
  25971. EXPECT_FALSE(target_saw_proxy_authz.load());
  25972. }
  25973. #endif
  25974. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25975. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25976. std::atomic<int> proxy_hits{0};
  25977. std::atomic<int> bypass_hits{0};
  25978. std::atomic<bool> proxy_saw_c_url{false};
  25979. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25980. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25981. proxy_hits++;
  25982. if (req.path.find("/start") != std::string::npos) {
  25983. res.status = 302;
  25984. res.set_header("Location", "http://127.0.0.1:" +
  25985. std::to_string(bypass_server.port()) +
  25986. "/middle");
  25987. return;
  25988. }
  25989. if (req.path.find("/end") != std::string::npos) {
  25990. proxy_saw_c_url = true;
  25991. res.set_content("c-via-proxy", "text/plain");
  25992. return;
  25993. }
  25994. res.set_content("unexpected", "text/plain");
  25995. });
  25996. // public.example's "advertised" port is arbitrary (the request never lands
  25997. // there — it goes through the proxy), but use a dynamic value to stay
  25998. // friendly with sharded parallel runs.
  25999. int public_port = bypass_server.port();
  26000. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26001. bypass_hits++;
  26002. res.status = 302;
  26003. res.set_header("Location", "http://public.example:" +
  26004. std::to_string(public_port) + "/end");
  26005. });
  26006. proxy_mock.listen();
  26007. bypass_server.listen();
  26008. Client cli("public.example", public_port);
  26009. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26010. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26011. cli.set_no_proxy({"127.0.0.1"});
  26012. cli.set_follow_location(true);
  26013. auto res = cli.Get("/start");
  26014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26015. EXPECT_EQ(StatusCode::OK_200, res->status);
  26016. EXPECT_EQ("c-via-proxy", res->body);
  26017. EXPECT_GE(proxy_hits.load(), 2);
  26018. EXPECT_GE(bypass_hits.load(), 1);
  26019. EXPECT_TRUE(proxy_saw_c_url.load());
  26020. }
  26021. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26022. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26023. // request reconnects to the correct endpoint.
  26024. std::atomic<int> proxy_hits{0};
  26025. std::atomic<int> target_hits{0};
  26026. no_proxy_test::ScopedServer proxy_mock, target;
  26027. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26028. proxy_hits++;
  26029. res.set_content("via-proxy", "text/plain");
  26030. });
  26031. target.svr().Get(".*", [&](const Request &, Response &res) {
  26032. target_hits++;
  26033. res.set_content("direct", "text/plain");
  26034. });
  26035. proxy_mock.listen();
  26036. target.listen();
  26037. Client cli("public.example", target.port());
  26038. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26039. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26040. cli.set_keep_alive(true);
  26041. auto res1 = cli.Get("/a");
  26042. ASSERT_TRUE(res1);
  26043. EXPECT_EQ("via-proxy", res1->body);
  26044. EXPECT_EQ(1, proxy_hits.load());
  26045. EXPECT_EQ(0, target_hits.load());
  26046. cli.set_no_proxy({"public.example"});
  26047. auto res2 = cli.Get("/b");
  26048. ASSERT_TRUE(res2);
  26049. EXPECT_EQ("direct", res2->body);
  26050. EXPECT_EQ(1, proxy_hits.load());
  26051. EXPECT_EQ(1, target_hits.load());
  26052. }
  26053. // Forward declarations (see the base64_encode note).
  26054. namespace httplib {
  26055. namespace detail {
  26056. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26057. int shutdown_socket(socket_t sock) noexcept;
  26058. } // namespace detail
  26059. } // namespace httplib
  26060. namespace proxy_tunnel_test {
  26061. const char *const kTunnelEstablished =
  26062. "HTTP/1.1 200 Connection established\r\n\r\n";
  26063. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26064. using ConnectReply = std::function<std::string(const std::string &head)>;
  26065. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26066. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26067. class ScopedConnectProxy {
  26068. public:
  26069. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26070. : forward_port_(forward_port), reply_(std::move(reply)) {
  26071. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26072. if (listen_sock_ == INVALID_SOCKET) { return; }
  26073. auto a = loopback(0);
  26074. auto addr = reinterpret_cast<sockaddr *>(&a);
  26075. socklen_t alen = sizeof(a);
  26076. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26077. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26078. ::listen(listen_sock_, 4) != 0) {
  26079. return;
  26080. }
  26081. port_ = ntohs(a.sin_port);
  26082. th_ = std::thread([this] { run(); });
  26083. }
  26084. ~ScopedConnectProxy() {
  26085. if (th_.joinable()) {
  26086. stop_ = true;
  26087. auto wake = connect_to(port_);
  26088. th_.join();
  26089. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26090. }
  26091. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26092. }
  26093. int port() const { return port_; }
  26094. int connect_hits() const { return connect_hits_.load(); }
  26095. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26096. std::string connect_request() const {
  26097. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26098. return connect_request_;
  26099. }
  26100. private:
  26101. static sockaddr_in loopback(int port) {
  26102. sockaddr_in a{};
  26103. a.sin_family = AF_INET;
  26104. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26105. a.sin_port = htons(static_cast<unsigned short>(port));
  26106. return a;
  26107. }
  26108. static socket_t connect_to(int port) {
  26109. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26110. if (sock == INVALID_SOCKET) { return sock; }
  26111. auto a = loopback(port);
  26112. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26113. detail::close_socket(sock);
  26114. return INVALID_SOCKET;
  26115. }
  26116. return sock;
  26117. }
  26118. static bool send_all(socket_t sock, const char *data, size_t size) {
  26119. while (size > 0) {
  26120. auto n = detail::send_socket(sock, data, size, 0);
  26121. if (n <= 0) { return false; }
  26122. data += n;
  26123. size -= static_cast<size_t>(n);
  26124. }
  26125. return true;
  26126. }
  26127. void run() {
  26128. for (;;) {
  26129. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26130. if (stop_) {
  26131. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26132. return;
  26133. }
  26134. if (client == INVALID_SOCKET) { continue; }
  26135. serve(client);
  26136. detail::close_socket(client);
  26137. }
  26138. }
  26139. void serve(socket_t client) {
  26140. std::string head;
  26141. char buf[2048];
  26142. while (head.find("\r\n\r\n") == std::string::npos) {
  26143. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26144. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26145. if (n <= 0) { return; }
  26146. head.append(buf, static_cast<size_t>(n));
  26147. }
  26148. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26149. connect_hits_++;
  26150. {
  26151. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26152. connect_request_ = head;
  26153. }
  26154. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26155. if (!send_all(client, res.data(), res.size()) ||
  26156. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26157. return;
  26158. }
  26159. auto origin = connect_to(forward_port_);
  26160. if (origin == INVALID_SOCKET) { return; }
  26161. // When either side stops, shut both down so the other pump returns too.
  26162. auto pump = [&](socket_t from, socket_t to) {
  26163. char b[8192];
  26164. for (;;) {
  26165. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26166. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26167. }
  26168. detail::shutdown_socket(client);
  26169. detail::shutdown_socket(origin);
  26170. };
  26171. std::thread up([&] { pump(client, origin); });
  26172. pump(origin, client);
  26173. up.join();
  26174. detail::close_socket(origin);
  26175. }
  26176. int forward_port_;
  26177. ConnectReply reply_;
  26178. socket_t listen_sock_ = INVALID_SOCKET;
  26179. int port_ = 0;
  26180. std::thread th_;
  26181. std::atomic<bool> stop_{false};
  26182. std::atomic<int> connect_hits_{0};
  26183. mutable std::mutex connect_request_mutex_;
  26184. std::string connect_request_;
  26185. };
  26186. } // namespace proxy_tunnel_test
  26187. #ifdef CPPHTTPLIB_SSL_ENABLED
  26188. namespace proxy_tunnel_test {
  26189. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26190. class ScopedSSLServer {
  26191. public:
  26192. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26193. port_ = svr_.bind_to_any_port("127.0.0.1");
  26194. }
  26195. ~ScopedSSLServer() {
  26196. svr_.stop();
  26197. if (th_.joinable()) { th_.join(); }
  26198. }
  26199. SSLServer &svr() { return svr_; }
  26200. int port() const { return port_; }
  26201. void listen() {
  26202. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26203. svr_.wait_until_ready();
  26204. }
  26205. private:
  26206. SSLServer svr_;
  26207. std::thread th_;
  26208. int port_ = 0;
  26209. };
  26210. // Sends one request through the CONNECT proxy to the TLS origin with a
  26211. // credential configured for each hop, and checks that each credential reaches
  26212. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26213. // origin's (every header in origin_headers) on the tunnelled request.
  26214. void CredentialsStayWithTheirHop(
  26215. const std::function<void(SSLClient &)> &set_credentials,
  26216. const std::string &scheme,
  26217. const std::vector<std::string> &origin_headers = {"Authorization"},
  26218. bool stream = false) {
  26219. std::atomic<int> origin_hits{0};
  26220. std::atomic<bool> origin_saw_proxy_authz{false};
  26221. std::atomic<bool> origin_saw_headers{false};
  26222. ScopedSSLServer origin;
  26223. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26224. origin_hits++;
  26225. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26226. origin_saw_headers =
  26227. std::all_of(origin_headers.begin(), origin_headers.end(),
  26228. [&](const std::string &h) { return req.has_header(h); });
  26229. res.set_content("ok", "text/plain");
  26230. });
  26231. origin.listen();
  26232. ScopedConnectProxy proxy(origin.port());
  26233. ASSERT_NE(0, proxy.port());
  26234. // Pinned to 127.0.0.1 for the same reason as the test below.
  26235. SSLClient cli("127.0.0.1", origin.port());
  26236. cli.enable_server_certificate_verification(false);
  26237. cli.set_proxy("127.0.0.1", proxy.port());
  26238. set_credentials(cli);
  26239. if (stream) {
  26240. auto handle = cli.open_stream("GET", "/x");
  26241. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26242. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26243. } else {
  26244. auto res = cli.Get("/x");
  26245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26246. EXPECT_EQ(StatusCode::OK_200, res->status);
  26247. }
  26248. EXPECT_EQ(1, origin_hits.load());
  26249. EXPECT_EQ(1, proxy.connect_hits());
  26250. EXPECT_TRUE(origin_saw_headers.load());
  26251. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26252. << "Proxy-Authorization must not be sent inside the tunnel";
  26253. auto connect_req = proxy.connect_request();
  26254. EXPECT_NE(std::string::npos,
  26255. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26256. for (const auto &h : origin_headers) {
  26257. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26258. << h << " must not be sent to the proxy on CONNECT";
  26259. }
  26260. }
  26261. } // namespace proxy_tunnel_test
  26262. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26263. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26264. [](SSLClient &cli) {
  26265. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26266. cli.set_basic_auth("origin-user", "origin-pass");
  26267. },
  26268. "Basic");
  26269. }
  26270. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26271. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26272. [](SSLClient &cli) {
  26273. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26274. cli.set_basic_auth("origin-user", "origin-pass");
  26275. },
  26276. "Basic", {"Authorization"}, true);
  26277. }
  26278. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26279. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26280. [](SSLClient &cli) {
  26281. cli.set_proxy_bearer_token_auth("proxy-token");
  26282. cli.set_bearer_token_auth("origin-token");
  26283. },
  26284. "Bearer");
  26285. }
  26286. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26287. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26288. [](SSLClient &cli) {
  26289. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26290. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26291. {"Cookie", "sid=origin-session"},
  26292. {"X-Api-Key", "origin-key"}});
  26293. },
  26294. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26295. }
  26296. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26297. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26298. // retry; otherwise proxy creds would be sent to the origin.
  26299. std::atomic<int> origin_hits{0};
  26300. std::atomic<bool> origin_saw_proxy_authz{false};
  26301. proxy_tunnel_test::ScopedSSLServer origin;
  26302. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26303. origin_hits++;
  26304. if (req.has_header("Proxy-Authorization")) {
  26305. origin_saw_proxy_authz = true;
  26306. }
  26307. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26308. res.set_header("Proxy-Authenticate",
  26309. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26310. "algorithm=MD5");
  26311. });
  26312. origin.listen();
  26313. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26314. ASSERT_NE(0, proxy.port());
  26315. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26316. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26317. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26318. // and answer with its own status, making this test flaky.
  26319. SSLClient cli("127.0.0.1", origin.port());
  26320. cli.enable_server_certificate_verification(false);
  26321. cli.set_proxy("127.0.0.1", proxy.port());
  26322. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26323. auto res = cli.Get("/x");
  26324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26325. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26326. EXPECT_EQ(1, origin_hits.load());
  26327. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26328. EXPECT_EQ(1, proxy.connect_hits());
  26329. }
  26330. #endif
  26331. namespace proxy_tunnel_test {
  26332. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26333. // anything else gets a 407 with `challenge`.
  26334. ConnectReply require_proxy_auth(const std::string &expected,
  26335. const std::string &challenge) {
  26336. return [=](const std::string &head) -> std::string {
  26337. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26338. std::string::npos) {
  26339. return kTunnelEstablished;
  26340. }
  26341. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26342. "Proxy-Authenticate: " +
  26343. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26344. };
  26345. }
  26346. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26347. // request, then echoes.
  26348. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26349. ws.send(
  26350. "authorization:" + req.get_header_value("Authorization") +
  26351. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26352. std::string msg;
  26353. while (ws.read(msg)) {
  26354. ws.send(msg);
  26355. }
  26356. }
  26357. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26358. class ScopedWebSocketOrigin {
  26359. public:
  26360. ScopedWebSocketOrigin() {
  26361. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26362. server_.listen();
  26363. }
  26364. int port() const { return server_.port(); }
  26365. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26366. std::string url() const {
  26367. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26368. }
  26369. private:
  26370. no_proxy_test::ScopedServer server_;
  26371. };
  26372. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26373. // passed as a constructor header, and checks that each reaches only its hop.
  26374. void WebSocketCredentialsStayWithTheirHop(
  26375. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26376. const std::string &proxy_authz, const std::string &origin_authz) {
  26377. ScopedWebSocketOrigin origin;
  26378. ScopedConnectProxy proxy(
  26379. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26380. ASSERT_NE(0, proxy.port());
  26381. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26382. client.set_proxy("127.0.0.1", proxy.port());
  26383. set_proxy_credentials(client);
  26384. auto res = client.connect();
  26385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26386. std::string msg;
  26387. ASSERT_TRUE(client.read(msg));
  26388. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26389. client.close();
  26390. EXPECT_EQ(1, proxy.connect_hits());
  26391. EXPECT_EQ(std::string::npos,
  26392. proxy.connect_request().find("\r\nAuthorization: "))
  26393. << "origin credentials must not be sent to the proxy";
  26394. }
  26395. } // namespace proxy_tunnel_test
  26396. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26397. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26398. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26399. ASSERT_NE(0, proxy.port());
  26400. ws::WebSocketClient client(origin.url());
  26401. client.set_proxy("127.0.0.1", proxy.port());
  26402. auto res = client.connect();
  26403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26404. std::string msg;
  26405. ASSERT_TRUE(client.read(msg));
  26406. ASSERT_TRUE(client.send("hello"));
  26407. ASSERT_TRUE(client.read(msg));
  26408. EXPECT_EQ("hello", msg);
  26409. client.close();
  26410. EXPECT_EQ(1, proxy.connect_hits());
  26411. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26412. auto connect_req = proxy.connect_request();
  26413. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26414. EXPECT_NE(std::string::npos,
  26415. connect_req.find("\r\nHost: " + target + "\r\n"));
  26416. }
  26417. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26418. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26419. [](ws::WebSocketClient &cli) {
  26420. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26421. },
  26422. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26423. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26424. }
  26425. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26426. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26427. [](ws::WebSocketClient &cli) {
  26428. cli.set_proxy_bearer_token_auth("proxy-token");
  26429. },
  26430. "Bearer proxy-token", "Bearer origin-token");
  26431. }
  26432. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26433. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26434. proxy_tunnel_test::ScopedConnectProxy proxy(
  26435. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26436. "Basic " + detail::base64_encode("proxy-user:"),
  26437. "Basic realm=\"proxy\""));
  26438. ASSERT_NE(0, proxy.port());
  26439. ws::WebSocketClient client(origin.url());
  26440. client.set_proxy("127.0.0.1", proxy.port());
  26441. client.set_proxy_basic_auth("proxy-user", "");
  26442. auto res = client.connect();
  26443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26444. client.close();
  26445. EXPECT_EQ(1, proxy.connect_hits());
  26446. }
  26447. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26448. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26449. proxy_tunnel_test::ScopedConnectProxy proxy(
  26450. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26451. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26452. ASSERT_NE(0, proxy.port());
  26453. ws::WebSocketClient client(origin.url());
  26454. client.set_proxy("127.0.0.1", proxy.port());
  26455. auto res = client.connect();
  26456. EXPECT_FALSE(res);
  26457. EXPECT_EQ(Error::ProxyConnection, res.error());
  26458. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26459. EXPECT_EQ("Basic realm=\"proxy\"",
  26460. res.get_header_value("Proxy-Authenticate"));
  26461. EXPECT_FALSE(client.is_open());
  26462. }
  26463. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26464. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26465. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26466. ASSERT_NE(0, proxy.port());
  26467. ws::WebSocketClient client(origin.url());
  26468. client.set_proxy("127.0.0.1", proxy.port());
  26469. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26470. client.set_no_proxy({"127.0.0.1"});
  26471. auto res = client.connect();
  26472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26473. std::string msg;
  26474. ASSERT_TRUE(client.read(msg));
  26475. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26476. << "proxy credentials must not reach a bypassed origin";
  26477. client.close();
  26478. EXPECT_EQ(0, proxy.connect_hits());
  26479. }
  26480. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26481. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26482. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26483. ASSERT_NE(0, proxy.port());
  26484. ws::WebSocketClient client(origin.url());
  26485. client.set_proxy("127.0.0.1", proxy.port());
  26486. ASSERT_TRUE(client.connect());
  26487. ASSERT_TRUE(client.connect());
  26488. client.close();
  26489. EXPECT_EQ(2, proxy.connect_hits());
  26490. }
  26491. #ifdef CPPHTTPLIB_SSL_ENABLED
  26492. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26493. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26494. proxy_tunnel_test::ScopedConnectProxy proxy(
  26495. origin.port(), [](const std::string &head) -> std::string {
  26496. if (head.find(
  26497. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26498. std::string::npos) {
  26499. return proxy_tunnel_test::kTunnelEstablished;
  26500. }
  26501. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26502. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26503. "nonce=\"abc\", algorithm=MD5\r\n"
  26504. "Content-Length: 0\r\n\r\n";
  26505. });
  26506. ASSERT_NE(0, proxy.port());
  26507. ws::WebSocketClient client(origin.url());
  26508. client.set_proxy("127.0.0.1", proxy.port());
  26509. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26510. auto res = client.connect();
  26511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26512. std::string msg;
  26513. ASSERT_TRUE(client.read(msg));
  26514. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26515. client.close();
  26516. EXPECT_EQ(2, proxy.connect_hits());
  26517. }
  26518. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26519. proxy_tunnel_test::ScopedSSLServer origin;
  26520. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26521. origin.listen();
  26522. proxy_tunnel_test::ScopedConnectProxy proxy(
  26523. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26524. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26525. ASSERT_NE(0, proxy.port());
  26526. ws::WebSocketClient client(
  26527. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26528. client.enable_server_certificate_verification(false);
  26529. client.set_proxy("127.0.0.1", proxy.port());
  26530. client.set_proxy_bearer_token_auth("proxy-token");
  26531. auto res = client.connect();
  26532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26533. std::string msg;
  26534. ASSERT_TRUE(client.read(msg));
  26535. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26536. << "Proxy-Authorization must not be sent inside the tunnel";
  26537. client.close();
  26538. EXPECT_EQ(1, proxy.connect_hits());
  26539. }
  26540. #endif