test.cc 1014 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168
  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. TEST_F(ServerTest, AcceptsChunkExtension) {
  6846. expect_chunked_body_status(cli_,
  6847. "4;name=value\r\ndech\r\n"
  6848. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6849. "0;last\r\n\r\n",
  6850. StatusCode::OK_200);
  6851. }
  6852. TEST_F(ServerTest, GetStreamed2) {
  6853. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6856. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6857. EXPECT_EQ(true, res->has_header("Content-Range"));
  6858. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6859. EXPECT_EQ(std::string("ab"), res->body);
  6860. }
  6861. TEST_F(ServerTest, GetStreamed) {
  6862. auto res = cli_.Get("/streamed");
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ(std::string("aaabbb"), res->body);
  6867. }
  6868. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6869. auto res = cli_.Get("/streamed-without-length",
  6870. Headers{make_range_header({{0, -1}})});
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(false, res->has_header("Content-Length"));
  6874. EXPECT_EQ(false, res->has_header("Content-Range"));
  6875. EXPECT_EQ(std::string("abcdefg"), res->body);
  6876. }
  6877. TEST_F(ServerTest, GetStreamedWithRange1) {
  6878. auto res =
  6879. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6882. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6883. EXPECT_EQ(true, res->has_header("Content-Range"));
  6884. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6885. EXPECT_EQ(std::string("def"), res->body);
  6886. }
  6887. TEST_F(ServerTest, GetStreamedWithRange2) {
  6888. auto res =
  6889. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6892. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6893. EXPECT_EQ(true, res->has_header("Content-Range"));
  6894. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6895. EXPECT_EQ(std::string("bcdefg"), res->body);
  6896. }
  6897. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6898. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6901. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6902. EXPECT_EQ(true, res->has_header("Content-Range"));
  6903. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6904. EXPECT_EQ(std::string("efg"), res->body);
  6905. }
  6906. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6907. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6908. // the entire representation.
  6909. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6910. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6913. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6914. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6915. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6916. }
  6917. }
  6918. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6919. auto res =
  6920. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6923. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6924. EXPECT_EQ(false, res->has_header("Content-Range"));
  6925. EXPECT_EQ(0U, res->body.size());
  6926. }
  6927. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6928. // Only a 206 is served as a partial representation. Under any other status
  6929. // `apply_ranges()` reported the full content length, so the body must match
  6930. // that header, and the content provider must never be asked for an offset
  6931. // outside the representation.
  6932. auto check = [&](int status, const char *range) {
  6933. auto path =
  6934. std::string("/streamed-with-range?status=") + std::to_string(status);
  6935. auto ctx = path + " Range: " + range;
  6936. auto res = cli_.Get(path, Headers{{"Range", range}});
  6937. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6938. EXPECT_EQ(status, res->status) << ctx;
  6939. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6941. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6942. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6943. };
  6944. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6945. check(403, "bytes=3-5");
  6946. // The offset is far past the representation.
  6947. check(403, "bytes=100000-100200");
  6948. // `first_pos` is still -1 here, and the bounds asserts in
  6949. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6950. check(403, "bytes=-3");
  6951. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6952. // multipart branch would have written one that is empty.
  6953. check(403, "bytes=1-2, 4-5");
  6954. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6955. // covers the whole representation.
  6956. check(200, "bytes=3-5");
  6957. check(200, "bytes=1-2, 4-5");
  6958. }
  6959. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6960. auto res =
  6961. cli_.Get("/streamed-with-range",
  6962. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6963. "92233720368547758079223372036854775807"}});
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6966. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6967. EXPECT_EQ(false, res->has_header("Content-Range"));
  6968. EXPECT_EQ(0U, res->body.size());
  6969. }
  6970. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6971. auto res = cli_.Get(
  6972. "/with-range",
  6973. Headers{{"Range",
  6974. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6975. {"Accept-Encoding", ""}});
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6978. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6979. EXPECT_EQ(true, res->has_header("Content-Range"));
  6980. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6981. EXPECT_EQ(std::string("abcdefg"), res->body);
  6982. }
  6983. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6984. auto res = cli_.Get("/with-range", Headers{
  6985. {"Range", "bytes=0-"},
  6986. {"Accept-Encoding", ""},
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6990. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6991. EXPECT_EQ(true, res->has_header("Content-Range"));
  6992. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6993. EXPECT_EQ(std::string("abcdefg"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6996. auto res = cli_.Get("/streamed-with-range",
  6997. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7000. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7001. EXPECT_EQ(false, res->has_header("Content-Range"));
  7002. EXPECT_EQ(267U, res->body.size());
  7003. // Check that both range contents are present
  7004. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7005. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7006. // Check that Content-Range headers are present for both ranges
  7007. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7008. std::string::npos);
  7009. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7010. std::string::npos);
  7011. }
  7012. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7013. Ranges ranges;
  7014. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7015. ranges.emplace_back(0, -1);
  7016. }
  7017. auto res = cli_.Get("/streamed-with-range?error",
  7018. Headers{{make_range_header(ranges)}});
  7019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7020. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7021. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7022. EXPECT_EQ(false, res->has_header("Content-Range"));
  7023. EXPECT_EQ(0U, res->body.size());
  7024. }
  7025. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7026. auto res = cli_.Get("/streamed-with-range",
  7027. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7030. EXPECT_EQ(5U, res->body.size());
  7031. // Check that overlapping ranges are coalesced into a single range
  7032. EXPECT_EQ("bcdef", res->body);
  7033. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7034. // Should be single range, not multipart
  7035. EXPECT_TRUE(res->has_header("Content-Range"));
  7036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7037. }
  7038. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7039. auto res = cli_.Get("/streamed-with-range",
  7040. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7043. EXPECT_EQ(268U, res->body.size());
  7044. // Check that both range contents are present
  7045. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7046. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7047. // Check that Content-Range headers are present for both ranges
  7048. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7049. std::string::npos);
  7050. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7051. std::string::npos);
  7052. }
  7053. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7054. auto res = cli_.Get("/streamed-with-range",
  7055. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. EXPECT_EQ(269U, res->body.size());
  7059. // Check that both duplicate range contents are present
  7060. size_t first_abc = res->body.find("abc\r\n");
  7061. EXPECT_TRUE(first_abc != std::string::npos);
  7062. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7063. EXPECT_TRUE(second_abc != std::string::npos);
  7064. // Check that Content-Range headers are present for both ranges
  7065. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7066. EXPECT_TRUE(first_range != std::string::npos);
  7067. size_t second_range =
  7068. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7069. EXPECT_TRUE(second_range != std::string::npos);
  7070. }
  7071. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7072. auto res =
  7073. cli_.Get("/streamed-with-range?error",
  7074. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7077. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7078. EXPECT_EQ(false, res->has_header("Content-Range"));
  7079. EXPECT_EQ(0U, res->body.size());
  7080. }
  7081. TEST_F(ServerTest, GetStreamedEndless) {
  7082. uint64_t offset = 0;
  7083. auto res = cli_.Get("/streamed-cancel",
  7084. [&](const char * /*data*/, uint64_t data_length) {
  7085. if (offset < 100) {
  7086. offset += data_length;
  7087. return true;
  7088. }
  7089. return false;
  7090. });
  7091. ASSERT_TRUE(!res);
  7092. EXPECT_EQ(Error::Canceled, res.error());
  7093. }
  7094. TEST_F(ServerTest, ClientStop) {
  7095. std::atomic_size_t count{4};
  7096. std::vector<std::thread> threads;
  7097. for (auto i = count.load(); i != 0; --i) {
  7098. threads.emplace_back([&]() {
  7099. auto res = cli_.Get("/streamed-cancel",
  7100. [&](const char *, uint64_t) { return true; });
  7101. --count;
  7102. ASSERT_TRUE(!res);
  7103. EXPECT_TRUE(res.error() == Error::Canceled ||
  7104. res.error() == Error::Read || res.error() == Error::Write);
  7105. });
  7106. }
  7107. std::this_thread::sleep_for(std::chrono::seconds(2));
  7108. while (count != 0) {
  7109. cli_.stop();
  7110. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7111. }
  7112. for (auto &t : threads) {
  7113. t.join();
  7114. }
  7115. }
  7116. TEST_F(ServerTest, GetWithRange1) {
  7117. auto res = cli_.Get("/with-range", Headers{
  7118. make_range_header({{3, 5}}),
  7119. {"Accept-Encoding", ""},
  7120. });
  7121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7123. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7124. EXPECT_EQ(true, res->has_header("Content-Range"));
  7125. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7126. EXPECT_EQ(std::string("def"), res->body);
  7127. }
  7128. TEST_F(ServerTest, GetWithRange2) {
  7129. auto res = cli_.Get("/with-range", Headers{
  7130. make_range_header({{1, -1}}),
  7131. {"Accept-Encoding", ""},
  7132. });
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7135. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7136. EXPECT_EQ(true, res->has_header("Content-Range"));
  7137. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7138. EXPECT_EQ(std::string("bcdefg"), res->body);
  7139. }
  7140. TEST_F(ServerTest, GetWithRange3) {
  7141. auto res = cli_.Get("/with-range", Headers{
  7142. make_range_header({{0, 0}}),
  7143. {"Accept-Encoding", ""},
  7144. });
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7147. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7148. EXPECT_EQ(true, res->has_header("Content-Range"));
  7149. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7150. EXPECT_EQ(std::string("a"), res->body);
  7151. }
  7152. TEST_F(ServerTest, GetWithRange4) {
  7153. auto res = cli_.Get("/with-range", Headers{
  7154. make_range_header({{-1, 2}}),
  7155. {"Accept-Encoding", ""},
  7156. });
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7159. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7160. EXPECT_EQ(true, res->has_header("Content-Range"));
  7161. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7162. EXPECT_EQ(std::string("fg"), res->body);
  7163. }
  7164. TEST_F(ServerTest, GetWithRange5) {
  7165. auto res = cli_.Get("/with-range", Headers{
  7166. make_range_header({{0, 5}}),
  7167. {"Accept-Encoding", ""},
  7168. });
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7171. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7172. EXPECT_EQ(true, res->has_header("Content-Range"));
  7173. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7174. EXPECT_EQ(std::string("abcdef"), res->body);
  7175. }
  7176. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7177. auto res =
  7178. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7181. }
  7182. TEST_F(ServerTest, GetWithRangeMultipart) {
  7183. auto res =
  7184. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(false, res->has_header("Content-Range"));
  7189. EXPECT_EQ(267U, res->body.size());
  7190. }
  7191. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7192. auto res = cli_.Get("/with-range",
  7193. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7196. }
  7197. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7198. auto res = cli_.Get("/with-range-customized-response",
  7199. Headers{{make_range_header({{1, 2}})}});
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7202. EXPECT_EQ(true, res->has_header("Content-Length"));
  7203. EXPECT_EQ(false, res->has_header("Content-Range"));
  7204. EXPECT_EQ(JSON_DATA, res->body);
  7205. }
  7206. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7207. auto res = cli_.Get("/with-range-customized-response",
  7208. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7211. EXPECT_EQ(true, res->has_header("Content-Length"));
  7212. EXPECT_EQ(false, res->has_header("Content-Range"));
  7213. EXPECT_EQ(JSON_DATA, res->body);
  7214. }
  7215. TEST_F(ServerTest, Issue1772) {
  7216. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7219. }
  7220. TEST_F(ServerTest, Issue609) {
  7221. auto res = cli_.Delete("/issue609");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ(std::string("ok"), res->body);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedChunked) {
  7227. auto res = cli_.Get("/streamed-chunked");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. EXPECT_EQ(std::string("123456789"), res->body);
  7231. }
  7232. TEST_F(ServerTest, GetStreamedChunked2) {
  7233. auto res = cli_.Get("/streamed-chunked2");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ(std::string("123456789"), res->body);
  7237. }
  7238. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7239. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::OK_200, res->status);
  7242. EXPECT_EQ(std::string("123456789"), res->body);
  7243. EXPECT_TRUE(res->has_header("Trailer"));
  7244. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7245. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7246. // Trailers are now stored separately from headers (security fix)
  7247. EXPECT_EQ(2U, res->trailers.size());
  7248. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7249. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7250. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7251. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7252. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7253. // Verify trailers are NOT in headers (security verification)
  7254. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7255. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7256. }
  7257. TEST_F(ServerTest, LargeChunkedPost) {
  7258. Request req;
  7259. req.method = "POST";
  7260. req.path = "/large-chunked";
  7261. std::string host_and_port;
  7262. host_and_port += HOST;
  7263. host_and_port += ":";
  7264. host_and_port += std::to_string(PORT);
  7265. req.headers.emplace("Host", host_and_port.c_str());
  7266. req.headers.emplace("Accept", "*/*");
  7267. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7268. req.headers.emplace("Content-Type", "text/plain");
  7269. req.headers.emplace("Content-Length", "0");
  7270. req.headers.emplace("Transfer-Encoding", "chunked");
  7271. std::string long_string(30 * 1024u, 'a');
  7272. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7273. // Attempt to make a large enough post to exceed OS buffers, to test that
  7274. // the server handles short reads if the full chunk data isn't available.
  7275. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7276. auto res = std::make_shared<Response>();
  7277. auto error = Error::Success;
  7278. auto ret = cli_.send(req, *res, error);
  7279. ASSERT_TRUE(ret);
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7283. auto res = cli_.Get("/remote_addr");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7287. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7288. }
  7289. TEST_F(ServerTest, GetMethodLocalAddr) {
  7290. auto res = cli_.Get("/local_addr");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7294. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7295. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7296. }
  7297. TEST_F(ServerTest, HTTPResponseSplitting) {
  7298. auto res = cli_.Get("/http_response_splitting");
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, SlowRequest) {
  7303. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7304. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7305. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7306. }
  7307. #if 0
  7308. TEST_F(ServerTest, SlowPost) {
  7309. char buffer[64 * 1024];
  7310. memset(buffer, 0x42, sizeof(buffer));
  7311. auto res = cli_.Post(
  7312. "/slowpost", 64 * 1024 * 1024,
  7313. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7314. auto ret = sink.write(buffer, sizeof(buffer));
  7315. EXPECT_TRUE(ret);
  7316. return true;
  7317. },
  7318. "text/plain");
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, SlowPostFail) {
  7323. char buffer[64 * 1024];
  7324. memset(buffer, 0x42, sizeof(buffer));
  7325. cli_.set_write_timeout(std::chrono::seconds(0));
  7326. auto res = cli_.Post(
  7327. "/slowpost", 64 * 1024 * 1024,
  7328. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7329. sink.write(buffer, sizeof(buffer));
  7330. return true;
  7331. },
  7332. "text/plain");
  7333. ASSERT_TRUE(!res);
  7334. EXPECT_EQ(Error::Write, res.error());
  7335. }
  7336. #endif
  7337. TEST_F(ServerTest, Put) {
  7338. auto res = cli_.Put("/put", "PUT", "text/plain");
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. EXPECT_EQ("PUT", res->body);
  7342. }
  7343. TEST_F(ServerTest, PutWithContentProvider) {
  7344. auto res = cli_.Put(
  7345. "/put", 3,
  7346. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7347. sink.os << "PUT";
  7348. return true;
  7349. },
  7350. "text/plain");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. EXPECT_EQ("PUT", res->body);
  7354. }
  7355. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7356. auto res = cli_.Post(
  7357. "/post", 42,
  7358. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7359. return false;
  7360. },
  7361. "text/plain");
  7362. ASSERT_TRUE(!res);
  7363. EXPECT_EQ(Error::Canceled, res.error());
  7364. }
  7365. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7366. auto res = cli_.Put(
  7367. "/put",
  7368. [](size_t /*offset*/, DataSink &sink) {
  7369. sink.os << "PUT";
  7370. sink.done();
  7371. return true;
  7372. },
  7373. "text/plain");
  7374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7375. EXPECT_EQ(StatusCode::OK_200, res->status);
  7376. EXPECT_EQ("PUT", res->body);
  7377. }
  7378. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7379. auto res = cli_.Post(
  7380. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7381. "text/plain");
  7382. ASSERT_TRUE(!res);
  7383. EXPECT_EQ(Error::Canceled, res.error());
  7384. }
  7385. TEST_F(ServerTest, PostLoopBack) {
  7386. std::string body;
  7387. auto res = cli_.Post(
  7388. "/post-loopback", 9,
  7389. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7390. EXPECT_EQ(9u, length);
  7391. sink.write("123", 3);
  7392. sink.write("456", 3);
  7393. sink.write("789", 3);
  7394. return true;
  7395. },
  7396. "text/plain",
  7397. [&body](const char *data, size_t data_length) {
  7398. body.append(data, data_length);
  7399. return true;
  7400. });
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ("123456789", body);
  7404. }
  7405. TEST_F(ServerTest, PutLoopBack) {
  7406. std::string body;
  7407. auto res = cli_.Put(
  7408. "/put-loopback", 9,
  7409. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7410. EXPECT_EQ(9u, length);
  7411. sink.write("123", 3);
  7412. sink.write("456", 3);
  7413. sink.write("789", 3);
  7414. return true;
  7415. },
  7416. "text/plain",
  7417. [&body](const char *data, size_t data_length) {
  7418. body.append(data, data_length);
  7419. return true;
  7420. });
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. EXPECT_EQ("123456789", body);
  7424. }
  7425. TEST_F(ServerTest, PatchLoopBack) {
  7426. std::string body;
  7427. auto res = cli_.Patch(
  7428. "/patch-loopback", 9,
  7429. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7430. EXPECT_EQ(9u, length);
  7431. sink.write("123", 3);
  7432. sink.write("456", 3);
  7433. sink.write("789", 3);
  7434. return true;
  7435. },
  7436. "text/plain",
  7437. [&body](const char *data, size_t data_length) {
  7438. body.append(data, data_length);
  7439. return true;
  7440. });
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("123456789", body);
  7444. }
  7445. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7446. std::string body;
  7447. auto res = cli_.Post(
  7448. "/post-loopback",
  7449. [](size_t /*offset*/, DataSink &sink) {
  7450. sink.write("123", 3);
  7451. sink.write("456", 3);
  7452. sink.write("789", 3);
  7453. sink.done();
  7454. return true;
  7455. },
  7456. "text/plain",
  7457. [&body](const char *data, size_t data_length) {
  7458. body.append(data, data_length);
  7459. return true;
  7460. });
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("123456789", body);
  7464. }
  7465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7466. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7467. cli_.set_compress(true);
  7468. auto res = cli_.Put(
  7469. "/put", 3,
  7470. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7471. sink.os << "PUT";
  7472. return true;
  7473. },
  7474. "text/plain");
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("PUT", res->body);
  7478. }
  7479. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7480. cli_.set_compress(true);
  7481. auto res = cli_.Post(
  7482. "/post", 42,
  7483. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7484. return false;
  7485. },
  7486. "text/plain");
  7487. ASSERT_TRUE(!res);
  7488. EXPECT_EQ(Error::Canceled, res.error());
  7489. }
  7490. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7491. cli_.set_compress(true);
  7492. auto res = cli_.Put(
  7493. "/put",
  7494. [](size_t /*offset*/, DataSink &sink) {
  7495. sink.os << "PUT";
  7496. sink.done();
  7497. return true;
  7498. },
  7499. "text/plain");
  7500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. EXPECT_EQ("PUT", res->body);
  7503. }
  7504. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7505. cli_.set_compress(true);
  7506. auto res = cli_.Post(
  7507. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7508. "text/plain");
  7509. ASSERT_TRUE(!res);
  7510. EXPECT_EQ(Error::Canceled, res.error());
  7511. }
  7512. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7513. cli_.set_compress(true);
  7514. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ(LARGE_DATA, res->body);
  7518. }
  7519. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7522. Client cli(s.c_str());
  7523. cli.enable_server_certificate_verification(false);
  7524. #else
  7525. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7526. Client cli(s.c_str());
  7527. #endif
  7528. cli.set_compress(true);
  7529. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. EXPECT_EQ(LARGE_DATA, res->body);
  7533. // The compressed size should be less than a 10th of the original. May vary
  7534. // depending on the zlib library.
  7535. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7536. static_cast<uint64_t>(10 * 1024 * 1024));
  7537. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7538. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7539. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7540. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7541. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7542. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7543. #endif
  7544. }
  7545. TEST_F(ServerTest, PutContentWithDeflate) {
  7546. cli_.set_compress(false);
  7547. Headers headers;
  7548. headers.emplace("Content-Encoding", "deflate");
  7549. // PUT in deflate format:
  7550. auto res = cli_.Put("/put", headers,
  7551. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(StatusCode::OK_200, res->status);
  7554. EXPECT_EQ("PUT", res->body);
  7555. }
  7556. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7557. Headers headers;
  7558. headers.emplace("Accept-Encoding", "gzip, deflate");
  7559. auto res = cli_.Get("/streamed-chunked", headers);
  7560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. EXPECT_EQ(std::string("123456789"), res->body);
  7563. }
  7564. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7565. Headers headers;
  7566. headers.emplace("Accept-Encoding", "gzip, deflate");
  7567. auto res = cli_.Get("/streamed-chunked2", headers);
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ(std::string("123456789"), res->body);
  7571. }
  7572. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7573. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST(GzipDecompressor, ChunkedDecompression) {
  7578. std::string data;
  7579. for (size_t i = 0; i < 32 * 1024; ++i) {
  7580. data.push_back(static_cast<char>('a' + i % 26));
  7581. }
  7582. std::string compressed_data;
  7583. {
  7584. httplib::detail::gzip_compressor compressor;
  7585. bool result = compressor.compress(
  7586. data.data(), data.size(),
  7587. /*last=*/true,
  7588. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7589. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7590. compressed_data_size);
  7591. return true;
  7592. });
  7593. ASSERT_TRUE(result);
  7594. }
  7595. std::string decompressed_data;
  7596. {
  7597. httplib::detail::gzip_decompressor decompressor;
  7598. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7599. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7600. size_t chunk_size = 130;
  7601. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7602. chunk_begin += chunk_size) {
  7603. size_t current_chunk_size =
  7604. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7605. bool result = decompressor.decompress(
  7606. compressed_data.data() + chunk_begin, current_chunk_size,
  7607. [&](const char *decompressed_data_chunk,
  7608. size_t decompressed_data_chunk_size) {
  7609. decompressed_data.insert(decompressed_data.size(),
  7610. decompressed_data_chunk,
  7611. decompressed_data_chunk_size);
  7612. return true;
  7613. });
  7614. ASSERT_TRUE(result);
  7615. }
  7616. }
  7617. ASSERT_EQ(data, decompressed_data);
  7618. }
  7619. TEST(GzipDecompressor, DeflateDecompression) {
  7620. std::string original_text = "Raw deflate without gzip";
  7621. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7622. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7623. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7624. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7625. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7626. std::string decompressed_data;
  7627. {
  7628. httplib::detail::gzip_decompressor decompressor;
  7629. bool result = decompressor.decompress(
  7630. compressed_data.data(), compressed_data.size(),
  7631. [&](const char *decompressed_data_chunk,
  7632. size_t decompressed_data_chunk_size) {
  7633. decompressed_data.insert(decompressed_data.size(),
  7634. decompressed_data_chunk,
  7635. decompressed_data_chunk_size);
  7636. return true;
  7637. });
  7638. ASSERT_TRUE(result);
  7639. }
  7640. ASSERT_EQ(original_text, decompressed_data);
  7641. }
  7642. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7643. std::string original_text = "Raw deflate without gzip";
  7644. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7645. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7646. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7647. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7648. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7649. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7650. std::string decompressed_data;
  7651. {
  7652. httplib::detail::gzip_decompressor decompressor;
  7653. bool result = decompressor.decompress(
  7654. compressed_data.data(), compressed_data.size(),
  7655. [&](const char *decompressed_data_chunk,
  7656. size_t decompressed_data_chunk_size) {
  7657. decompressed_data.insert(decompressed_data.size(),
  7658. decompressed_data_chunk,
  7659. decompressed_data_chunk_size);
  7660. return true;
  7661. });
  7662. ASSERT_TRUE(result);
  7663. }
  7664. ASSERT_EQ(original_text, decompressed_data);
  7665. }
  7666. #endif
  7667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7668. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7669. Headers headers;
  7670. headers.emplace("Accept-Encoding", "br");
  7671. auto res = cli_.Get("/streamed-chunked", headers);
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. EXPECT_EQ(std::string("123456789"), res->body);
  7675. }
  7676. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7677. Headers headers;
  7678. headers.emplace("Accept-Encoding", "br");
  7679. auto res = cli_.Get("/streamed-chunked2", headers);
  7680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7681. EXPECT_EQ(StatusCode::OK_200, res->status);
  7682. EXPECT_EQ(std::string("123456789"), res->body);
  7683. }
  7684. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7685. cli_.set_compress(true);
  7686. auto res = cli_.Put(
  7687. "/put", 3,
  7688. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7689. sink.os << "PUT";
  7690. return true;
  7691. },
  7692. "text/plain");
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ("PUT", res->body);
  7696. }
  7697. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7698. cli_.set_compress(true);
  7699. auto res = cli_.Put(
  7700. "/put",
  7701. [](size_t /*offset*/, DataSink &sink) {
  7702. sink.os << "PUT";
  7703. sink.done();
  7704. return true;
  7705. },
  7706. "text/plain");
  7707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7708. EXPECT_EQ(StatusCode::OK_200, res->status);
  7709. EXPECT_EQ("PUT", res->body);
  7710. }
  7711. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7712. cli_.set_compress(true);
  7713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ(LARGE_DATA, res->body);
  7717. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7718. }
  7719. #endif
  7720. TEST_F(ServerTest, Patch) {
  7721. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. EXPECT_EQ(StatusCode::OK_200, res->status);
  7724. EXPECT_EQ("PATCH", res->body);
  7725. }
  7726. TEST_F(ServerTest, Delete) {
  7727. auto res = cli_.Delete("/delete");
  7728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. EXPECT_EQ("DELETE", res->body);
  7731. }
  7732. TEST_F(ServerTest, DeleteContentReceiver) {
  7733. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. EXPECT_EQ("content", res->body);
  7737. }
  7738. TEST_F(ServerTest, Options) {
  7739. auto res = cli_.Options("*");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7743. EXPECT_TRUE(res->body.empty());
  7744. }
  7745. TEST_F(ServerTest, URL) {
  7746. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST_F(ServerTest, ArrayParam) {
  7751. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. }
  7755. TEST_F(ServerTest, ArrayParamValues) {
  7756. auto res =
  7757. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. }
  7761. TEST_F(ServerTest, NoMultipleHeaders) {
  7762. Headers headers = {{"Content-Length", "5"}};
  7763. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7764. "text/plain");
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, PostContentReceiver) {
  7769. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. ASSERT_EQ(StatusCode::OK_200, res->status);
  7772. ASSERT_EQ("content", res->body);
  7773. }
  7774. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7775. UploadFormDataItems items = {
  7776. {"text1", "text default", "", ""},
  7777. {"text2", "aωb", "", ""},
  7778. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7779. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7780. {"file3", "", "", "application/octet-stream"},
  7781. };
  7782. auto res = cli_.Post("/content_receiver", items);
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. }
  7786. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7787. UploadFormDataItems items = {
  7788. {"text1", "text default", "", ""},
  7789. {"text2", "aωb", "", ""},
  7790. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7791. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7792. {"file3", "", "", "application/octet-stream"},
  7793. };
  7794. auto boundary = std::string("+++++");
  7795. std::string body;
  7796. for (const auto &item : items) {
  7797. body += "--" + boundary + "\r\n";
  7798. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7799. if (!item.filename.empty()) {
  7800. body += "; filename=\"" + item.filename + "\"";
  7801. }
  7802. body += "\r\n";
  7803. if (!item.content_type.empty()) {
  7804. body += "Content-Type: " + item.content_type + "\r\n";
  7805. }
  7806. body += "\r\n";
  7807. body += item.content + "\r\n";
  7808. }
  7809. body += "--" + boundary + "--\r\n";
  7810. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7811. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7813. EXPECT_EQ(StatusCode::OK_200, res->status);
  7814. }
  7815. TEST(MultipartFormDataTest, FieldEscaping) {
  7816. Server svr;
  7817. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7818. const ContentReader &content_reader) {
  7819. ASSERT_TRUE(req.is_multipart_form_data());
  7820. std::vector<FormData> received;
  7821. content_reader(
  7822. [&](const FormData &file) {
  7823. received.push_back(file);
  7824. return true;
  7825. },
  7826. [&](const char *data, size_t data_length) {
  7827. received.back().content.append(data, data_length);
  7828. return true;
  7829. });
  7830. // '"', CR and LF in names and filenames are escaped following the
  7831. // WHATWG HTML standard, so each part still parses as a single part
  7832. // with no injected headers. Content types get CR/LF escaped too,
  7833. // while '"' (legal there, e.g. quoted charset) is preserved.
  7834. ASSERT_EQ(4U, received.size());
  7835. EXPECT_EQ("na%22me", received[0].name);
  7836. EXPECT_EQ("quoted name", received[0].content);
  7837. EXPECT_EQ("file", received[1].name);
  7838. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7839. received[1].filename);
  7840. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7841. EXPECT_EQ("injected", received[1].content);
  7842. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7843. EXPECT_EQ("my%22file.txt", received[2].filename);
  7844. EXPECT_EQ("cr lf name", received[2].content);
  7845. EXPECT_EQ("typed", received[3].name);
  7846. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7847. received[3].content_type);
  7848. EXPECT_EQ("typed content", received[3].content);
  7849. });
  7850. auto port = svr.bind_to_any_port("localhost");
  7851. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7852. auto se = detail::scope_exit([&] {
  7853. svr.stop();
  7854. t.join();
  7855. ASSERT_FALSE(svr.is_running());
  7856. });
  7857. svr.wait_until_ready();
  7858. Client cli("localhost", port);
  7859. UploadFormDataItems items = {
  7860. {"na\"me", "quoted name", "", ""},
  7861. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7862. "application/octet-stream"},
  7863. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7864. {"typed", "typed content", "",
  7865. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7866. };
  7867. auto res = cli.Post("/post", items);
  7868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7869. EXPECT_EQ(StatusCode::OK_200, res->status);
  7870. }
  7871. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7872. const UploadFormDataItems items = {
  7873. {"name1", "Content 1", "", ""},
  7874. {"name2", "Content 2", "file2.txt", "text/plain"},
  7875. };
  7876. Server svr;
  7877. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7878. const ContentReader &content_reader) {
  7879. ASSERT_TRUE(req.is_multipart_form_data());
  7880. std::vector<FormData> received;
  7881. content_reader(
  7882. [&](const FormData &file) {
  7883. received.push_back(file);
  7884. return true;
  7885. },
  7886. [&](const char *data, size_t data_length) {
  7887. received.back().content.append(data, data_length);
  7888. return true;
  7889. });
  7890. ASSERT_EQ(2U, received.size());
  7891. EXPECT_EQ("name1", received[0].name);
  7892. EXPECT_EQ("Content 1", received[0].content);
  7893. EXPECT_EQ("name2", received[1].name);
  7894. EXPECT_EQ("Content 2", received[1].content);
  7895. EXPECT_EQ("file2.txt", received[1].filename);
  7896. EXPECT_EQ("text/plain", received[1].content_type);
  7897. });
  7898. auto port = svr.bind_to_any_port("localhost");
  7899. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7900. auto se = detail::scope_exit([&] {
  7901. svr.stop();
  7902. t.join();
  7903. ASSERT_FALSE(svr.is_running());
  7904. });
  7905. svr.wait_until_ready();
  7906. Client cli("localhost", port);
  7907. // Whole-body serialization with a generated boundary
  7908. {
  7909. MultipartFormDataWriter writer;
  7910. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7911. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7912. writer.content_type());
  7913. auto body = writer.serialize(items);
  7914. EXPECT_EQ(body.size(), writer.content_length(items));
  7915. auto res = cli.Post("/post", body, writer.content_type());
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ(StatusCode::OK_200, res->status);
  7918. }
  7919. // Per-part framing with a custom boundary via a content provider
  7920. {
  7921. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7922. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7923. MultipartFormDataWriter writer("custom-boundary_123");
  7924. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7925. std::string body;
  7926. for (const auto &item : items) {
  7927. body += writer.item_begin(item);
  7928. body += item.content;
  7929. body += MultipartFormDataWriter::item_end();
  7930. }
  7931. body += writer.finish();
  7932. EXPECT_EQ(body.size(), writer.content_length(items));
  7933. auto res = cli.Post(
  7934. "/post", body.size(),
  7935. [&](size_t offset, size_t length, DataSink &sink) {
  7936. sink.write(body.data() + offset, length);
  7937. return true;
  7938. },
  7939. writer.content_type());
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::OK_200, res->status);
  7942. }
  7943. }
  7944. TEST_F(ServerTest, PostContentReceiverGzip) {
  7945. cli_.set_compress(true);
  7946. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. ASSERT_EQ(StatusCode::OK_200, res->status);
  7949. ASSERT_EQ("content", res->body);
  7950. }
  7951. TEST_F(ServerTest, PutContentReceiver) {
  7952. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. ASSERT_EQ(StatusCode::OK_200, res->status);
  7955. ASSERT_EQ("content", res->body);
  7956. }
  7957. TEST_F(ServerTest, PatchContentReceiver) {
  7958. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. ASSERT_EQ(StatusCode::OK_200, res->status);
  7961. ASSERT_EQ("content", res->body);
  7962. }
  7963. template <typename ClientType>
  7964. void TestWithHeadersAndContentReceiver(
  7965. ClientType &cli,
  7966. std::function<Result(ClientType &, const std::string &, const Headers &,
  7967. const std::string &, const std::string &,
  7968. ContentReceiver, DownloadProgress)>
  7969. request_func) {
  7970. Headers headers;
  7971. headers.emplace("X-Custom-Header", "test-value");
  7972. std::string received_body;
  7973. auto res = request_func(
  7974. cli, "/content_receiver", headers, "content", "application/json",
  7975. [&](const char *data, size_t data_length) {
  7976. received_body.append(data, data_length);
  7977. return true;
  7978. },
  7979. nullptr);
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. EXPECT_EQ("content", received_body);
  7983. }
  7984. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7985. #ifdef CPPHTTPLIB_SSL_ENABLED
  7986. using ClientT = SSLClient;
  7987. #else
  7988. using ClientT = Client;
  7989. #endif
  7990. TestWithHeadersAndContentReceiver<ClientT>(
  7991. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7992. const std::string &body, const std::string &content_type,
  7993. ContentReceiver receiver, DownloadProgress progress) {
  7994. return cli.Post(path, headers, body, content_type, receiver, progress);
  7995. });
  7996. }
  7997. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7998. #ifdef CPPHTTPLIB_SSL_ENABLED
  7999. using ClientT = SSLClient;
  8000. #else
  8001. using ClientT = Client;
  8002. #endif
  8003. TestWithHeadersAndContentReceiver<ClientT>(
  8004. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8005. const std::string &body, const std::string &content_type,
  8006. ContentReceiver receiver, DownloadProgress progress) {
  8007. return cli.Put(path, headers, body, content_type, receiver, progress);
  8008. });
  8009. }
  8010. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8011. #ifdef CPPHTTPLIB_SSL_ENABLED
  8012. using ClientT = SSLClient;
  8013. #else
  8014. using ClientT = Client;
  8015. #endif
  8016. TestWithHeadersAndContentReceiver<ClientT>(
  8017. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8018. const std::string &body, const std::string &content_type,
  8019. ContentReceiver receiver, DownloadProgress progress) {
  8020. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8021. });
  8022. }
  8023. template <typename ClientType>
  8024. void TestWithHeadersAndContentReceiverWithProgress(
  8025. ClientType &cli,
  8026. std::function<Result(ClientType &, const std::string &, const Headers &,
  8027. const std::string &, const std::string &,
  8028. ContentReceiver, DownloadProgress)>
  8029. request_func) {
  8030. Headers headers;
  8031. headers.emplace("X-Test-Header", "progress-test");
  8032. std::string received_body;
  8033. auto progress_called = false;
  8034. auto res = request_func(
  8035. cli, "/content_receiver", headers, "content", "text/plain",
  8036. [&](const char *data, size_t data_length) {
  8037. received_body.append(data, data_length);
  8038. return true;
  8039. },
  8040. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8041. progress_called = true;
  8042. return true;
  8043. });
  8044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. EXPECT_EQ("content", received_body);
  8047. EXPECT_TRUE(progress_called);
  8048. }
  8049. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8050. #ifdef CPPHTTPLIB_SSL_ENABLED
  8051. using ClientT = SSLClient;
  8052. #else
  8053. using ClientT = Client;
  8054. #endif
  8055. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8056. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8057. const std::string &body, const std::string &content_type,
  8058. ContentReceiver receiver, DownloadProgress progress) {
  8059. return cli.Post(path, headers, body, content_type, receiver, progress);
  8060. });
  8061. }
  8062. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8063. #ifdef CPPHTTPLIB_SSL_ENABLED
  8064. using ClientT = SSLClient;
  8065. #else
  8066. using ClientT = Client;
  8067. #endif
  8068. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8069. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8070. const std::string &body, const std::string &content_type,
  8071. ContentReceiver receiver, DownloadProgress progress) {
  8072. return cli.Put(path, headers, body, content_type, receiver, progress);
  8073. });
  8074. }
  8075. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8076. #ifdef CPPHTTPLIB_SSL_ENABLED
  8077. using ClientT = SSLClient;
  8078. #else
  8079. using ClientT = Client;
  8080. #endif
  8081. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8082. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8083. const std::string &body, const std::string &content_type,
  8084. ContentReceiver receiver, DownloadProgress progress) {
  8085. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8086. });
  8087. }
  8088. template <typename ClientType>
  8089. void TestWithHeadersAndContentReceiverError(
  8090. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8091. const Headers &, const std::string &,
  8092. const std::string &, ContentReceiver)>
  8093. request_func) {
  8094. Headers headers;
  8095. headers.emplace("X-Error-Test", "true");
  8096. std::string received_body;
  8097. auto receiver_failed = false;
  8098. auto res =
  8099. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8100. [&](const char *data, size_t data_length) {
  8101. received_body.append(data, data_length);
  8102. receiver_failed = true;
  8103. return false;
  8104. });
  8105. ASSERT_FALSE(res);
  8106. EXPECT_TRUE(receiver_failed);
  8107. }
  8108. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8109. #ifdef CPPHTTPLIB_SSL_ENABLED
  8110. using ClientT = SSLClient;
  8111. #else
  8112. using ClientT = Client;
  8113. #endif
  8114. TestWithHeadersAndContentReceiverError<ClientT>(
  8115. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8116. const std::string &body, const std::string &content_type,
  8117. ContentReceiver receiver) {
  8118. return cli.Post(path, headers, body, content_type, receiver);
  8119. });
  8120. }
  8121. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8122. #ifdef CPPHTTPLIB_SSL_ENABLED
  8123. using ClientT = SSLClient;
  8124. #else
  8125. using ClientT = Client;
  8126. #endif
  8127. TestWithHeadersAndContentReceiverError<ClientT>(
  8128. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8129. const std::string &body, const std::string &content_type,
  8130. ContentReceiver receiver) {
  8131. return cli.Put(path, headers, body, content_type, receiver);
  8132. });
  8133. }
  8134. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8135. #ifdef CPPHTTPLIB_SSL_ENABLED
  8136. using ClientT = SSLClient;
  8137. #else
  8138. using ClientT = Client;
  8139. #endif
  8140. TestWithHeadersAndContentReceiverError<ClientT>(
  8141. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8142. const std::string &body, const std::string &content_type,
  8143. ContentReceiver receiver) {
  8144. return cli.Patch(path, headers, body, content_type, receiver);
  8145. });
  8146. }
  8147. TEST_F(ServerTest, PostQueryStringAndBody) {
  8148. auto res =
  8149. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. ASSERT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. TEST_F(ServerTest, HTTP2Magic) {
  8154. Request req;
  8155. req.method = "PRI";
  8156. req.path = "*";
  8157. req.body = "SM";
  8158. auto res = std::make_shared<Response>();
  8159. auto error = Error::Success;
  8160. auto ret = cli_.send(req, *res, error);
  8161. ASSERT_TRUE(ret);
  8162. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8163. }
  8164. TEST_F(ServerTest, KeepAlive) {
  8165. auto res = cli_.Get("/hi");
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8169. EXPECT_EQ("Hello World!", res->body);
  8170. res = cli_.Get("/hi");
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8174. EXPECT_EQ("Hello World!", res->body);
  8175. res = cli_.Get("/hi");
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8179. EXPECT_EQ("Hello World!", res->body);
  8180. res = cli_.Get("/not-exist");
  8181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8183. res = cli_.Post("/empty", "", "text/plain");
  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("empty", res->body);
  8188. EXPECT_EQ("close", res->get_header_value("Connection"));
  8189. res = cli_.Post(
  8190. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8191. "text/plain");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8195. EXPECT_EQ("empty", res->body);
  8196. cli_.set_keep_alive(false);
  8197. res = cli_.Get("/last-request");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. EXPECT_EQ("close", res->get_header_value("Connection"));
  8201. }
  8202. TEST_F(ServerTest, TooManyRedirect) {
  8203. cli_.set_follow_location(true);
  8204. auto res = cli_.Get("/redirect/0");
  8205. ASSERT_TRUE(!res);
  8206. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8207. }
  8208. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8209. Request req;
  8210. req.method = "FOOBAR";
  8211. req.path = "/hi";
  8212. cli_.set_keep_alive(true);
  8213. auto res = cli_.send(req);
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8216. EXPECT_EQ("close", res->get_header_value("Connection"));
  8217. EXPECT_FALSE(cli_.is_socket_open());
  8218. }
  8219. TEST_F(ServerTest, CustomRouteReadsBody) {
  8220. const std::string xml =
  8221. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8222. Request req;
  8223. req.method = "PROPFIND";
  8224. req.path = "/dav/dir";
  8225. req.set_header("Depth", "1");
  8226. req.body = xml;
  8227. auto res = cli_.send(req);
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8230. EXPECT_EQ(xml, res->body);
  8231. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8232. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8233. }
  8234. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8235. Request req;
  8236. req.method = "PROPFIND";
  8237. req.path = "/dav/42";
  8238. auto res = cli_.send(req);
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8241. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8242. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8243. }
  8244. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8245. Request req;
  8246. req.method = "PROPFIND";
  8247. req.path = "/dav-re/123";
  8248. auto res = cli_.send(req);
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8251. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8252. }
  8253. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8254. Request req;
  8255. req.method = "MKCOL";
  8256. req.path = "/dav-mkcol";
  8257. auto res = cli_.send(req);
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::Created_201, res->status);
  8260. }
  8261. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8262. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8263. Request req;
  8264. req.method = "REPORT";
  8265. req.path = "/dav-report";
  8266. req.body = xml;
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ(xml, res->body);
  8271. }
  8272. // A content reader route must fire even when the request carries no body,
  8273. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8274. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8275. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8276. Request req;
  8277. req.method = "REPORT";
  8278. req.path = "/dav-report";
  8279. auto res = cli_.send(req);
  8280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8281. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8282. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8283. }
  8284. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/not-dav";
  8288. auto res = cli_.send(req);
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8291. }
  8292. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8293. Request req;
  8294. req.method = "UNLOCK";
  8295. req.path = "/dav/dir";
  8296. cli_.set_keep_alive(true);
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8300. EXPECT_EQ("close", res->get_header_value("Connection"));
  8301. EXPECT_FALSE(cli_.is_socket_open());
  8302. }
  8303. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8304. // The mount point serves this path, but only for GET and HEAD.
  8305. auto get_res = cli_.Get("/dir/index.html");
  8306. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8307. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8308. Request req;
  8309. req.method = "PROPFIND";
  8310. req.path = "/dir/index.html";
  8311. auto res = cli_.send(req);
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8314. }
  8315. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8316. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8317. cli_.set_keep_alive(true);
  8318. for (auto i = 0; i < 2; i++) {
  8319. Request req;
  8320. req.method = "PROPFIND";
  8321. req.path = "/dav/dir";
  8322. req.body = xml;
  8323. auto res = cli_.send(req);
  8324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8325. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8326. EXPECT_EQ(xml, res->body);
  8327. EXPECT_TRUE(cli_.is_socket_open());
  8328. }
  8329. // A built-in method must still be served on the same connection.
  8330. cli_.set_keep_alive(false);
  8331. auto res = cli_.Get("/hi");
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("close", res->get_header_value("Connection"));
  8335. }
  8336. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8337. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8338. Request req;
  8339. req.method = "PROPFIND";
  8340. req.path = "/dav/dir";
  8341. req.set_header("Expect", "100-continue");
  8342. req.body = xml;
  8343. auto res = cli_.send(req);
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8346. EXPECT_EQ(xml, res->body);
  8347. }
  8348. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8350. TEST_F(ServerTest, Gzip) {
  8351. Headers headers;
  8352. headers.emplace("Accept-Encoding", "gzip, deflate");
  8353. auto res = cli_.Get("/compress", headers);
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8357. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8358. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8359. "7890123456789012345678901234567890",
  8360. res->body);
  8361. EXPECT_EQ(StatusCode::OK_200, res->status);
  8362. }
  8363. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8364. Headers headers;
  8365. headers.emplace("Accept-Encoding", "gzip, deflate");
  8366. auto res = cli_.Get("/compress-with-charset", headers);
  8367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8368. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8369. EXPECT_EQ("application/json; charset=utf-8",
  8370. res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8372. "7890123456789012345678901234567890",
  8373. res->body);
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8377. Headers headers;
  8378. headers.emplace("Accept-Encoding", "");
  8379. auto res = cli_.Get("/compress", headers);
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8383. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8384. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8385. "7890123456789012345678901234567890",
  8386. res->body);
  8387. EXPECT_EQ(StatusCode::OK_200, res->status);
  8388. }
  8389. TEST_F(ServerTest, GzipWithContentReceiver) {
  8390. Headers headers;
  8391. headers.emplace("Accept-Encoding", "gzip, deflate");
  8392. std::string body;
  8393. auto res =
  8394. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8395. EXPECT_EQ(100U, data_length);
  8396. body.append(data, data_length);
  8397. return true;
  8398. });
  8399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8402. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8404. "7890123456789012345678901234567890",
  8405. body);
  8406. EXPECT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8409. Headers headers;
  8410. headers.emplace("Accept-Encoding", "gzip, deflate");
  8411. cli_.set_decompress(false);
  8412. auto res = cli_.Get("/compress", headers);
  8413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8414. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8415. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8416. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8417. EXPECT_EQ(33U, res->body.size());
  8418. EXPECT_EQ(StatusCode::OK_200, res->status);
  8419. }
  8420. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8421. Headers headers;
  8422. headers.emplace("Accept-Encoding", "");
  8423. std::string body;
  8424. auto res =
  8425. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8426. EXPECT_EQ(100U, data_length);
  8427. body.append(data, data_length);
  8428. return true;
  8429. });
  8430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8431. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8432. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8433. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8434. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8435. "7890123456789012345678901234567890",
  8436. body);
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. }
  8439. TEST_F(ServerTest, NoGzip) {
  8440. Headers headers;
  8441. headers.emplace("Accept-Encoding", "gzip, deflate");
  8442. auto res = cli_.Get("/nocompress", headers);
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8445. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8446. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8447. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8448. "7890123456789012345678901234567890",
  8449. res->body);
  8450. EXPECT_EQ(StatusCode::OK_200, res->status);
  8451. }
  8452. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8453. Headers headers;
  8454. headers.emplace("Accept-Encoding", "gzip, deflate");
  8455. std::string body;
  8456. auto res = cli_.Get("/nocompress", headers,
  8457. [&](const char *data, size_t data_length) {
  8458. EXPECT_EQ(100U, data_length);
  8459. body.append(data, data_length);
  8460. return true;
  8461. });
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8464. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, MultipartFormDataGzip) {
  8472. UploadFormDataItems items = {
  8473. {"key1", "test", "", ""},
  8474. {"key2", "--abcdefg123", "", ""},
  8475. };
  8476. cli_.set_compress(true);
  8477. auto res = cli_.Post("/compress-multipart", items);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. }
  8481. #endif
  8482. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8483. // Static file compression is opt-in, so these run their own server rather than
  8484. // flipping it on for the shared ServerTest fixture, which would silently
  8485. // rewrite what every other static file test is asserting.
  8486. class StaticFileCompressionTest : public ::testing::Test {
  8487. protected:
  8488. void TearDown() override {
  8489. if (t_.joinable()) {
  8490. svr_.stop();
  8491. t_.join();
  8492. }
  8493. }
  8494. int start(const std::function<void(Server &)> &configure = nullptr) {
  8495. // Serves the same tree as a directory of build-time compressed assets
  8496. // would be served: the mount point names the coding the files are already
  8497. // stored in. Registered before "/" so it is the one that matches.
  8498. svr_.set_mount_point("/pre-encoded", "./www",
  8499. {{"Content-Encoding", "gzip"}});
  8500. svr_.set_mount_point("/", "./www");
  8501. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8502. res.set_file_content("./www/dir/index.html", "text/html");
  8503. });
  8504. svr_.Get("/pre-encoded-file-content",
  8505. [](const Request & /*req*/, Response &res) {
  8506. res.set_header("Content-Encoding", "gzip");
  8507. res.set_file_content("./www/dir/index.html", "text/html");
  8508. });
  8509. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8510. res.set_content_provider(
  8511. 6, "text/plain",
  8512. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8513. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8514. return true;
  8515. });
  8516. });
  8517. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8518. res.set_content_provider(
  8519. 1000, "text/plain",
  8520. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8521. if (offset < 100) {
  8522. std::string data(100, 'A');
  8523. sink.write(data.data(), data.size());
  8524. return true;
  8525. }
  8526. std::this_thread::sleep_for(std::chrono::seconds(2));
  8527. std::string data(900, 'B');
  8528. sink.write(data.data(), data.size());
  8529. return true;
  8530. });
  8531. });
  8532. if (configure) { configure(svr_); }
  8533. auto port = svr_.bind_to_any_port(HOST);
  8534. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8535. svr_.wait_until_ready();
  8536. return port;
  8537. }
  8538. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8539. // Every file under ./www except 1MB.txt is smaller than the default
  8540. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8541. // it out of the way.
  8542. static void enable_without_floor(Server &svr) {
  8543. svr.set_static_file_compression(true);
  8544. svr.set_static_file_compression_min_length(0);
  8545. }
  8546. Server svr_;
  8547. std::thread t_;
  8548. };
  8549. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8550. auto port = start();
  8551. Client cli(HOST, port);
  8552. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8556. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ(1048576U, res->body.size());
  8558. }
  8559. TEST_F(StaticFileCompressionTest, MountPoint) {
  8560. auto port = start(enable);
  8561. Client cli(HOST, port);
  8562. cli.set_decompress(false);
  8563. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_EQ(StatusCode::OK_200, res->status);
  8566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8568. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8569. // The response stays self-delimiting: a length, not a chunked body.
  8570. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8571. EXPECT_EQ(std::to_string(res->body.size()),
  8572. res->get_header_value("Content-Length"));
  8573. EXPECT_LT(res->body.size(), 1048576U);
  8574. EXPECT_FALSE(res->body.empty());
  8575. }
  8576. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8577. auto port = start(enable);
  8578. Client cli(HOST, port);
  8579. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8583. EXPECT_EQ(1048576U, res->body.size());
  8584. }
  8585. TEST_F(StaticFileCompressionTest, FileContent) {
  8586. auto port = start(enable_without_floor);
  8587. Client cli(HOST, port);
  8588. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8592. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8593. EXPECT_EQ(104U, res->body.size());
  8594. }
  8595. // A handler that serves an already-encoded file names the coding itself. The
  8596. // file-backed path decided its coding from Accept-Encoding and the content
  8597. // type alone, so it compressed the stored bytes a second time and appended a
  8598. // second Content-Encoding field line.
  8599. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8600. auto port = start(enable_without_floor);
  8601. Client cli(HOST, port);
  8602. cli.set_decompress(false);
  8603. auto res = cli.Get("/pre-encoded-file-content",
  8604. Headers{{"Accept-Encoding", "gzip"}});
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::OK_200, res->status);
  8607. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. // Vary belongs to a coding the server chose, and it chose none here.
  8610. EXPECT_FALSE(res->has_header("Vary"));
  8611. // The file travels exactly as it is stored on disk.
  8612. EXPECT_EQ(104U, res->body.size());
  8613. }
  8614. // The 1MB file clears the default floor, so this one runs the configuration a
  8615. // deployment would actually have.
  8616. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8617. auto port = start(enable);
  8618. Client cli(HOST, port);
  8619. cli.set_decompress(false);
  8620. auto res =
  8621. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8625. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8626. EXPECT_FALSE(res->has_header("Vary"));
  8627. EXPECT_EQ(1048576U, res->body.size());
  8628. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8629. }
  8630. TEST_F(StaticFileCompressionTest, Head) {
  8631. auto port = start(enable);
  8632. Client cli(HOST, port);
  8633. cli.set_decompress(false);
  8634. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8635. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8636. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8638. EXPECT_EQ(StatusCode::OK_200, res->status);
  8639. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8640. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8641. // HEAD still reports the size a GET would return.
  8642. EXPECT_EQ(get->get_header_value("Content-Length"),
  8643. res->get_header_value("Content-Length"));
  8644. EXPECT_TRUE(res->body.empty());
  8645. }
  8646. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8647. auto port = start(enable);
  8648. Client cli(HOST, port);
  8649. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8650. {"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8653. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8654. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8655. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8656. EXPECT_EQ("cd", res->body);
  8657. }
  8658. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8659. auto port = start(enable);
  8660. Client cli(HOST, port);
  8661. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8665. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8666. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8667. }
  8668. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8669. auto port = start(enable);
  8670. Client cli(HOST, port);
  8671. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8673. EXPECT_EQ(StatusCode::OK_200, res->status);
  8674. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8675. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8676. EXPECT_TRUE(res->body.empty());
  8677. }
  8678. TEST_F(StaticFileCompressionTest, MinLength) {
  8679. auto port = start(enable);
  8680. Client cli(HOST, port);
  8681. // 104 bytes, well under the default floor. Compressing it would add the
  8682. // gzip header and trailer to a body that already fits in one packet.
  8683. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8685. EXPECT_EQ(StatusCode::OK_200, res->status);
  8686. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8687. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8688. }
  8689. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8690. auto port = start([](Server &svr) {
  8691. svr.set_static_file_compression(true);
  8692. svr.set_static_file_compression_min_length(1);
  8693. });
  8694. Client cli(HOST, port);
  8695. cli.set_decompress(false);
  8696. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8699. // A 9-byte file comes back larger than it went in, because gzip's header and
  8700. // trailer outweigh anything deflate can save. That is the end of the range
  8701. // the floor exists to keep out.
  8702. EXPECT_GT(res->body.size(), 9U);
  8703. }
  8704. TEST_F(StaticFileCompressionTest, MaxLength) {
  8705. auto port = start([](Server &svr) {
  8706. svr.set_static_file_compression(true);
  8707. svr.set_static_file_compression_min_length(0);
  8708. svr.set_static_file_compression_max_length(1024);
  8709. });
  8710. Client cli(HOST, port);
  8711. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8712. // defines `small` as a macro on Windows.
  8713. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8714. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8715. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8716. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8717. // Under it: compressed.
  8718. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8719. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8720. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8721. }
  8722. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8723. auto port = start(enable_without_floor);
  8724. Client cli(HOST, port);
  8725. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8726. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8727. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8728. auto identity_etag = identity->get_header_value("ETag");
  8729. ASSERT_FALSE(identity_etag.empty());
  8730. auto gzipped =
  8731. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8732. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8733. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8734. auto gzip_etag = gzipped->get_header_value("ETag");
  8735. ASSERT_FALSE(gzip_etag.empty());
  8736. // Two representations, two validators.
  8737. EXPECT_NE(identity_etag, gzip_etag);
  8738. // Each one revalidates against the request that would produce it...
  8739. auto fresh =
  8740. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8741. {"If-None-Match", gzip_etag}});
  8742. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8743. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8744. auto fresh_identity =
  8745. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8746. {"If-None-Match", identity_etag}});
  8747. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8748. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8749. // ...and not against the other representation.
  8750. auto crossed =
  8751. cli.Get("/dir/index.html",
  8752. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8753. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8754. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8755. }
  8756. // The opt-in covers responses the server reads off disk itself. A caller's own
  8757. // known-length provider keeps its Content-Length and, more importantly, keeps
  8758. // delivering incrementally: routing it through a compressor would hold every
  8759. // write back until zlib's window filled.
  8760. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8761. auto port = start(enable);
  8762. Client cli(HOST, port);
  8763. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8765. EXPECT_EQ(StatusCode::OK_200, res->status);
  8766. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8767. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8768. EXPECT_EQ("aaabbb", res->body);
  8769. }
  8770. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8771. auto port = start(enable);
  8772. Client cli(HOST, port);
  8773. cli.set_read_timeout(1, 0);
  8774. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8775. Headers{{"Accept-Encoding", "gzip"}});
  8776. ASSERT_TRUE(handle.is_valid());
  8777. // The provider writes 100 bytes and then stalls for longer than the read
  8778. // timeout. Those first bytes have to arrive anyway: run the response through
  8779. // a compressor and zlib holds them until its window fills, so the read would
  8780. // come back empty instead.
  8781. char buf[256];
  8782. auto n = handle.read(buf, sizeof(buf));
  8783. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8784. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8785. }
  8786. #endif
  8787. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8788. TEST_F(ServerTest, Brotli) {
  8789. Headers headers;
  8790. headers.emplace("Accept-Encoding", "br");
  8791. auto res = cli_.Get("/compress", headers);
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8794. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8795. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8796. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8797. "7890123456789012345678901234567890",
  8798. res->body);
  8799. EXPECT_EQ(StatusCode::OK_200, res->status);
  8800. }
  8801. #endif
  8802. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8803. TEST_F(ServerTest, Zstd) {
  8804. Headers headers;
  8805. headers.emplace("Accept-Encoding", "zstd");
  8806. auto res = cli_.Get("/compress", headers);
  8807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8808. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8810. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8812. "7890123456789012345678901234567890",
  8813. res->body);
  8814. EXPECT_EQ(StatusCode::OK_200, res->status);
  8815. }
  8816. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8817. Headers headers;
  8818. headers.emplace("Accept-Encoding", "");
  8819. auto res = cli_.Get("/compress", headers);
  8820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8821. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8823. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8824. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8825. "7890123456789012345678901234567890",
  8826. res->body);
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. }
  8829. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8830. Headers headers;
  8831. headers.emplace("Accept-Encoding", "zstd");
  8832. std::string body;
  8833. auto res =
  8834. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8835. EXPECT_EQ(100U, data_length);
  8836. body.append(data, data_length);
  8837. return true;
  8838. });
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "zstd");
  8851. cli_.set_decompress(false);
  8852. auto res = cli_.Get("/compress", headers);
  8853. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8854. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8855. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8856. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  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(StatusCode::OK_200, res->status);
  8862. ASSERT_EQ(26U, res->body.size());
  8863. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8864. 0);
  8865. }
  8866. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8867. Headers headers;
  8868. headers.emplace("Accept-Encoding", "");
  8869. std::string body;
  8870. auto res =
  8871. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8872. EXPECT_EQ(100U, data_length);
  8873. body.append(data, data_length);
  8874. return true;
  8875. });
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8881. "7890123456789012345678901234567890",
  8882. body);
  8883. EXPECT_EQ(StatusCode::OK_200, res->status);
  8884. }
  8885. TEST_F(ServerTest, NoZstd) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "zstd");
  8888. auto res = cli_.Get("/nocompress", headers);
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8891. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8892. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8893. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8894. "7890123456789012345678901234567890",
  8895. res->body);
  8896. EXPECT_EQ(StatusCode::OK_200, res->status);
  8897. }
  8898. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8899. Headers headers;
  8900. headers.emplace("Accept-Encoding", "zstd");
  8901. std::string body;
  8902. auto res = cli_.Get("/nocompress", headers,
  8903. [&](const char *data, size_t data_length) {
  8904. EXPECT_EQ(100U, data_length);
  8905. body.append(data, data_length);
  8906. return true;
  8907. });
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8910. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8912. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8913. "7890123456789012345678901234567890",
  8914. body);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. }
  8917. // TODO: How to enable zstd ??
  8918. TEST_F(ServerTest, MultipartFormDataZstd) {
  8919. UploadFormDataItems items = {
  8920. {"key1", "test", "", ""},
  8921. {"key2", "--abcdefg123", "", ""},
  8922. };
  8923. Headers headers;
  8924. headers.emplace("Accept-Encoding", "zstd");
  8925. cli_.set_compress(true);
  8926. auto res = cli_.Post("/compress-multipart", headers, items);
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8931. Headers headers;
  8932. headers.emplace("Accept-Encoding", "zstd");
  8933. cli_.set_compress(true);
  8934. auto res = cli_.Put(
  8935. "/put", headers, 3,
  8936. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8937. sink.os << "PUT";
  8938. return true;
  8939. },
  8940. "text/plain");
  8941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8942. EXPECT_EQ(StatusCode::OK_200, res->status);
  8943. EXPECT_EQ("PUT", res->body);
  8944. }
  8945. // Pre-compression logging tests
  8946. TEST_F(ServerTest, PreCompressionLogging) {
  8947. // Test data for compression (matches the actual /compress endpoint content)
  8948. const std::string test_content =
  8949. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8950. "3456789012345678901234567890";
  8951. // Variables to capture logging data
  8952. std::string pre_compression_body;
  8953. std::string pre_compression_content_type;
  8954. std::string pre_compression_content_encoding;
  8955. std::string post_compression_body;
  8956. std::string post_compression_content_type;
  8957. std::string post_compression_content_encoding;
  8958. // Set up pre-compression logger
  8959. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8960. const Response &res) {
  8961. pre_compression_body = res.body;
  8962. pre_compression_content_type = res.get_header_value("Content-Type");
  8963. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8964. });
  8965. // Set up post-compression logger
  8966. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8967. post_compression_body = res.body;
  8968. post_compression_content_type = res.get_header_value("Content-Type");
  8969. post_compression_content_encoding =
  8970. res.get_header_value("Content-Encoding");
  8971. });
  8972. // Test with gzip compression
  8973. Headers headers;
  8974. headers.emplace("Accept-Encoding", "gzip");
  8975. auto res = cli_.Get("/compress", headers);
  8976. // Verify response was compressed
  8977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8978. EXPECT_EQ(StatusCode::OK_200, res->status);
  8979. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8980. // Verify pre-compression logger captured uncompressed content
  8981. EXPECT_EQ(test_content, pre_compression_body);
  8982. EXPECT_EQ("text/plain", pre_compression_content_type);
  8983. EXPECT_TRUE(pre_compression_content_encoding
  8984. .empty()); // No encoding header before compression
  8985. // Verify post-compression logger captured compressed content
  8986. EXPECT_NE(test_content,
  8987. post_compression_body); // Should be different after compression
  8988. EXPECT_EQ("text/plain", post_compression_content_type);
  8989. EXPECT_EQ("gzip", post_compression_content_encoding);
  8990. // Verify compressed content is smaller
  8991. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8992. }
  8993. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8994. const std::string test_content =
  8995. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8996. "3456789012345678901234567890";
  8997. std::string pre_compression_body;
  8998. std::string post_compression_body;
  8999. svr_.set_pre_compression_logger(
  9000. [&](const Request & /*req*/, const Response &res) {
  9001. pre_compression_body = res.body;
  9002. });
  9003. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9004. post_compression_body = res.body;
  9005. });
  9006. Headers headers;
  9007. headers.emplace("Accept-Encoding", "br");
  9008. auto res = cli_.Get("/compress", headers);
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::OK_200, res->status);
  9011. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9012. // Verify pre-compression content is uncompressed
  9013. EXPECT_EQ(test_content, pre_compression_body);
  9014. // Verify post-compression content is compressed
  9015. EXPECT_NE(test_content, post_compression_body);
  9016. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9017. }
  9018. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9019. const std::string test_content =
  9020. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9021. "3456789012345678901234567890";
  9022. std::string pre_compression_body;
  9023. std::string post_compression_body;
  9024. svr_.set_pre_compression_logger(
  9025. [&](const Request & /*req*/, const Response &res) {
  9026. pre_compression_body = res.body;
  9027. });
  9028. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9029. post_compression_body = res.body;
  9030. });
  9031. // Request without compression (use /nocompress endpoint)
  9032. Headers headers;
  9033. auto res = cli_.Get("/nocompress", headers);
  9034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9035. EXPECT_EQ(StatusCode::OK_200, res->status);
  9036. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9037. // Pre-compression logger should not be called when no compression is applied
  9038. EXPECT_TRUE(
  9039. pre_compression_body.empty()); // Pre-compression logger not called
  9040. EXPECT_EQ(
  9041. test_content,
  9042. post_compression_body); // Post-compression logger captures final content
  9043. }
  9044. TEST_F(ServerTest, LoggerSeesContentLength) {
  9045. size_t logged_content_length = 0;
  9046. std::string logged_content_length_header;
  9047. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9048. logged_content_length = res.content_length_;
  9049. logged_content_length_header = res.get_header_value("Content-Length");
  9050. });
  9051. auto res = cli_.Get("/nocompress");
  9052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9053. EXPECT_EQ(StatusCode::OK_200, res->status);
  9054. EXPECT_EQ(res->body.size(), logged_content_length);
  9055. EXPECT_EQ(std::to_string(logged_content_length),
  9056. logged_content_length_header);
  9057. }
  9058. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9059. const std::string test_content =
  9060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9061. "3456789012345678901234567890";
  9062. std::string pre_compression_body;
  9063. bool pre_logger_called = false;
  9064. // Set only pre-compression logger
  9065. svr_.set_pre_compression_logger(
  9066. [&](const Request & /*req*/, const Response &res) {
  9067. pre_compression_body = res.body;
  9068. pre_logger_called = true;
  9069. });
  9070. Headers headers;
  9071. headers.emplace("Accept-Encoding", "gzip");
  9072. auto res = cli_.Get("/compress", headers);
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_EQ(StatusCode::OK_200, res->status);
  9075. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9076. // Verify pre-compression logger was called
  9077. EXPECT_TRUE(pre_logger_called);
  9078. EXPECT_EQ(test_content, pre_compression_body);
  9079. }
  9080. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9081. {
  9082. // Test with Expect: 100-continue header - success case
  9083. // Server returns 100 Continue, client sends body, server returns 200 OK
  9084. Request req;
  9085. req.method = "POST";
  9086. req.path = "/post-large";
  9087. req.set_header("Expect", "100-continue");
  9088. req.body = LARGE_DATA;
  9089. Response res;
  9090. auto error = Error::Success;
  9091. cli_.set_keep_alive(true);
  9092. auto ret = cli_.send(req, res, error);
  9093. EXPECT_TRUE(ret);
  9094. EXPECT_EQ(StatusCode::OK_200, res.status);
  9095. EXPECT_EQ(LARGE_DATA, res.body);
  9096. }
  9097. {
  9098. // Test with Expect: 100-continue header - error case
  9099. // Client should not send the body when server returns an error
  9100. Request req;
  9101. req.method = "POST";
  9102. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9103. req.set_header("Expect", "100-continue");
  9104. req.body = LARGE_DATA;
  9105. Response res;
  9106. auto error = Error::Success;
  9107. auto start = std::chrono::high_resolution_clock::now();
  9108. cli_.set_keep_alive(true);
  9109. auto ret = cli_.send(req, res, error);
  9110. auto end = std::chrono::high_resolution_clock::now();
  9111. auto elapsed =
  9112. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9113. .count();
  9114. // With Expect: 100-continue, request completes successfully but with error
  9115. EXPECT_TRUE(ret);
  9116. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9117. EXPECT_EQ("close", res.get_header_value("Connection"));
  9118. EXPECT_FALSE(cli_.is_socket_open());
  9119. EXPECT_LE(elapsed, 2000);
  9120. }
  9121. {
  9122. // Send an extra GET request to ensure error recovery without hanging
  9123. Request req;
  9124. req.method = "GET";
  9125. req.path = "/hi";
  9126. auto start = std::chrono::high_resolution_clock::now();
  9127. auto res = cli_.send(req);
  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. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9133. EXPECT_EQ(StatusCode::OK_200, res->status);
  9134. EXPECT_EQ("Hello World!", res->body);
  9135. EXPECT_LE(elapsed, 500);
  9136. }
  9137. }
  9138. TEST(ZstdDecompressor, ChunkedDecompression) {
  9139. std::string data;
  9140. for (size_t i = 0; i < 32 * 1024; ++i) {
  9141. data.push_back(static_cast<char>('a' + i % 26));
  9142. }
  9143. std::string compressed_data;
  9144. {
  9145. httplib::detail::zstd_compressor compressor;
  9146. bool result = compressor.compress(
  9147. data.data(), data.size(),
  9148. /*last=*/true,
  9149. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9150. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9151. compressed_data_size);
  9152. return true;
  9153. });
  9154. ASSERT_TRUE(result);
  9155. }
  9156. std::string decompressed_data;
  9157. {
  9158. httplib::detail::zstd_decompressor decompressor;
  9159. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9160. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9161. size_t chunk_size = 130;
  9162. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9163. chunk_begin += chunk_size) {
  9164. size_t current_chunk_size =
  9165. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9166. bool result = decompressor.decompress(
  9167. compressed_data.data() + chunk_begin, current_chunk_size,
  9168. [&](const char *decompressed_data_chunk,
  9169. size_t decompressed_data_chunk_size) {
  9170. decompressed_data.insert(decompressed_data.size(),
  9171. decompressed_data_chunk,
  9172. decompressed_data_chunk_size);
  9173. return true;
  9174. });
  9175. ASSERT_TRUE(result);
  9176. }
  9177. }
  9178. ASSERT_EQ(data, decompressed_data);
  9179. }
  9180. TEST(ZstdDecompressor, Decompress) {
  9181. std::string original_text = "Compressed with ZSTD";
  9182. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9183. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9184. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9185. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9186. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9187. std::string decompressed_data;
  9188. {
  9189. httplib::detail::zstd_decompressor decompressor;
  9190. bool result = decompressor.decompress(
  9191. compressed_data.data(), compressed_data.size(),
  9192. [&](const char *decompressed_data_chunk,
  9193. size_t decompressed_data_chunk_size) {
  9194. decompressed_data.insert(decompressed_data.size(),
  9195. decompressed_data_chunk,
  9196. decompressed_data_chunk_size);
  9197. return true;
  9198. });
  9199. ASSERT_TRUE(result);
  9200. }
  9201. ASSERT_EQ(original_text, decompressed_data);
  9202. }
  9203. #endif
  9204. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9205. // separate chunks so that the server sees each part in its own read(). Used to
  9206. // place a read boundary at a specific offset of a request body.
  9207. static bool send_request_in_parts(time_t read_timeout_sec,
  9208. const std::vector<std::string> &parts,
  9209. std::string *resp = nullptr,
  9210. int port = PORT) {
  9211. auto error = Error::Success;
  9212. auto client_sock = detail::create_client_socket(
  9213. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9214. /*connection_timeout_sec=*/5, 0,
  9215. /*read_timeout_sec=*/5, 0,
  9216. /*write_timeout_sec=*/5, 0, std::string(), error);
  9217. if (client_sock == INVALID_SOCKET) { return false; }
  9218. auto ret = detail::process_client_socket(
  9219. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9220. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9221. for (size_t i = 0; i < parts.size(); i++) {
  9222. const auto &part = parts[i];
  9223. if (part.size() !=
  9224. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9225. return false;
  9226. }
  9227. if (i + 1 < parts.size()) {
  9228. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9229. }
  9230. }
  9231. char buf[512];
  9232. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9233. while (line_reader.getline()) {
  9234. if (resp) { *resp += line_reader.ptr(); }
  9235. }
  9236. return true;
  9237. });
  9238. detail::close_socket(client_sock);
  9239. return ret;
  9240. }
  9241. // Sends a raw request to a server listening at HOST:PORT.
  9242. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9243. std::string *resp = nullptr, int port = PORT) {
  9244. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9245. }
  9246. #ifdef CPPHTTPLIB_SSL_ENABLED
  9247. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9249. ASSERT_TRUE(svr.is_valid());
  9250. svr.set_read_timeout(1, 0);
  9251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9252. auto se = detail::scope_exit([&] {
  9253. svr.stop();
  9254. t.join();
  9255. ASSERT_FALSE(svr.is_running());
  9256. });
  9257. svr.wait_until_ready();
  9258. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9259. // keeps each wait well within the read timeout. The server gives up a
  9260. // second in, so the bytes sent after that fail.
  9261. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9262. parts.resize(26, std::string(1, '\0'));
  9263. EXPECT_FALSE(send_request_in_parts(5, parts));
  9264. }
  9265. #endif
  9266. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9267. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9268. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9269. const std::vector<std::string> &parts,
  9270. std::string *resp = nullptr,
  9271. int port = PORT) {
  9272. auto error = Error::Success;
  9273. auto sock = detail::create_client_socket(
  9274. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9275. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9276. /*write_timeout_sec=*/5, 0, std::string(), error);
  9277. if (sock == INVALID_SOCKET) { return false; }
  9278. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9279. auto ctx = SSL_CTX_new(TLS_client_method());
  9280. auto ssl = SSL_new(ctx);
  9281. auto ssl_se = detail::scope_exit([&] {
  9282. SSL_free(ssl);
  9283. SSL_CTX_free(ctx);
  9284. });
  9285. SSL_set_fd(ssl, static_cast<int>(sock));
  9286. if (SSL_connect(ssl) != 1) { return false; }
  9287. for (size_t i = 0; i < parts.size(); i++) {
  9288. const auto &part = parts[i];
  9289. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9290. static_cast<int>(part.size())) {
  9291. return false;
  9292. }
  9293. if (i + 1 < parts.size()) {
  9294. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9295. }
  9296. }
  9297. char buf[512];
  9298. int n;
  9299. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9300. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9301. }
  9302. return true;
  9303. }
  9304. #endif
  9305. // The request line, then a header value a byte at a time.
  9306. static std::vector<std::string> slow_request_head_parts() {
  9307. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9308. parts.resize(26, "a");
  9309. parts.emplace_back("\r\n\r\n");
  9310. return parts;
  9311. }
  9312. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9313. // within the one-second read timeout. The server gives up a second in, before
  9314. // the head is complete.
  9315. static void
  9316. expect_slow_request_head_dropped(Server &svr,
  9317. const std::function<std::string()> &send) {
  9318. std::atomic<bool> handled(false);
  9319. svr.Get("/", [&](const Request &, Response &res) {
  9320. handled = true;
  9321. res.set_content("ok", "text/plain");
  9322. });
  9323. svr.set_read_timeout(1, 0);
  9324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9325. auto se = detail::scope_exit([&] {
  9326. svr.stop();
  9327. t.join();
  9328. ASSERT_FALSE(svr.is_running());
  9329. });
  9330. svr.wait_until_ready();
  9331. auto resp = send();
  9332. EXPECT_FALSE(handled);
  9333. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9334. }
  9335. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9336. Server svr;
  9337. expect_slow_request_head_dropped(svr, [] {
  9338. std::string resp;
  9339. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9340. return resp;
  9341. });
  9342. }
  9343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9344. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9346. ASSERT_TRUE(svr.is_valid());
  9347. expect_slow_request_head_dropped(svr, [] {
  9348. std::string resp;
  9349. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9350. return resp;
  9351. });
  9352. }
  9353. #endif
  9354. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9355. Server svr;
  9356. std::string header_value;
  9357. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9358. header_value = req.get_header_value("foo");
  9359. res.set_content("ok", "text/plain");
  9360. });
  9361. thread t = thread([&] { svr.listen(HOST, PORT); });
  9362. auto se = detail::scope_exit([&] {
  9363. svr.stop();
  9364. t.join();
  9365. ASSERT_FALSE(svr.is_running());
  9366. });
  9367. svr.wait_until_ready();
  9368. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9369. // like characters are not treated the same - use vertical tab and escape.
  9370. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9371. "foo: \t \v bar \x1B\t \r\n"
  9372. "Connection: close\r\n"
  9373. "\r\n";
  9374. std::string res;
  9375. ASSERT_TRUE(send_request(5, req, &res));
  9376. EXPECT_EQ(header_value, "");
  9377. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9378. }
  9379. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9380. Server svr;
  9381. std::string received;
  9382. svr.Get("/order", [&](const Request &req, Response &res) {
  9383. received = entries_to_string(req.headers);
  9384. res.set_content("ok", "text/plain");
  9385. });
  9386. auto port = svr.bind_to_any_port(HOST);
  9387. thread t = thread([&] { svr.listen_after_bind(); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. ASSERT_FALSE(svr.is_running());
  9392. });
  9393. svr.wait_until_ready();
  9394. const std::string req = "GET /order HTTP/1.1\r\n"
  9395. "Host: localhost\r\n"
  9396. "X-First: 1\r\n"
  9397. "X-Dup: a\r\n"
  9398. "X-Second: 2\r\n"
  9399. "X-Dup: b\r\n"
  9400. "Connection: close\r\n"
  9401. "\r\n";
  9402. std::string res;
  9403. ASSERT_TRUE(send_request(5, req, &res, port));
  9404. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9405. EXPECT_EQ(
  9406. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9407. received);
  9408. }
  9409. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9410. Server svr;
  9411. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9412. res.set_header("Set-Cookie", "first=1");
  9413. res.set_header("X-Between", "y");
  9414. res.set_header("Set-Cookie", "second=2");
  9415. res.set_content("ok", "text/plain");
  9416. });
  9417. auto port = svr.bind_to_any_port(HOST);
  9418. thread t = thread([&] { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. Client cli(HOST, port);
  9426. auto res = cli.Get("/cookies");
  9427. ASSERT_TRUE(res);
  9428. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9429. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9430. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9431. }
  9432. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9433. Server svr;
  9434. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9435. auto i = new int(0);
  9436. res.set_header("Trailer", "X-Safe, X-Reflected");
  9437. res.set_chunked_content_provider(
  9438. "text/plain",
  9439. [i](size_t /*offset*/, DataSink &sink) {
  9440. if (*i == 0) {
  9441. sink.os << "body";
  9442. } else {
  9443. Headers trailer;
  9444. // A valid trailer that must survive.
  9445. trailer.emplace("X-Safe", "safe");
  9446. // Attacker-controlled value carrying CR/LF (response splitting).
  9447. trailer.emplace("X-Reflected",
  9448. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9449. // Attacker-controlled name carrying CR/LF.
  9450. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9451. sink.done_with_trailer(trailer);
  9452. }
  9453. (*i)++;
  9454. return true;
  9455. },
  9456. [i](bool /*success*/) { delete i; });
  9457. });
  9458. thread t = thread([&] { svr.listen(HOST, PORT); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9466. "Host: " + HOST +
  9467. "\r\n"
  9468. "Connection: close\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(5, req, &res));
  9472. // The injected fields must not appear anywhere in the raw response.
  9473. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9474. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9475. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9476. // Invalid trailers are dropped entirely, matching set_header().
  9477. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9478. // The valid trailer still passes through.
  9479. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9480. }
  9481. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9482. Server svr;
  9483. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9484. // res.headers is a public field an application can populate directly,
  9485. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9486. // A valid header that must survive.
  9487. res.headers.emplace("X-Safe", "safe");
  9488. // Attacker-controlled value carrying CR/LF (response splitting).
  9489. res.headers.emplace("X-Reflected",
  9490. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9491. // Attacker-controlled name carrying CR/LF.
  9492. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9493. res.set_content("body", "text/plain");
  9494. });
  9495. thread t = thread([&] { svr.listen(HOST, PORT); });
  9496. auto se = detail::scope_exit([&] {
  9497. svr.stop();
  9498. t.join();
  9499. ASSERT_FALSE(svr.is_running());
  9500. });
  9501. svr.wait_until_ready();
  9502. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9503. "Host: " + HOST +
  9504. "\r\n"
  9505. "Connection: close\r\n"
  9506. "\r\n";
  9507. std::string res;
  9508. ASSERT_TRUE(send_request(5, req, &res));
  9509. // The injected fields must not appear anywhere in the raw response.
  9510. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9511. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9512. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9513. // Invalid headers are dropped entirely, matching set_header().
  9514. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9515. // The valid header still passes through.
  9516. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9517. }
  9518. // Forward declaration: in split builds split.py strips `inline` and moves the
  9519. // definition into httplib.cc, so detail::write_request_line is not visible from
  9520. // the public httplib.h. Re-declaring it here lets the tests link against the
  9521. // symbol in both header-only and split builds.
  9522. namespace httplib {
  9523. namespace detail {
  9524. ssize_t write_request_line(Stream &strm, const std::string &method,
  9525. const std::string &path);
  9526. } // namespace detail
  9527. } // namespace httplib
  9528. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9529. // A well-formed target is written verbatim.
  9530. {
  9531. detail::BufferStream strm;
  9532. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9533. EXPECT_GT(n, 0);
  9534. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9535. }
  9536. // A target carrying CR/LF, SP or other control octets must be rejected
  9537. // before anything reaches the wire, otherwise it splits the request line and
  9538. // injects a header or a whole request.
  9539. const std::string evil_targets[] = {
  9540. "/a\r\nInjected: pwned",
  9541. "/a\rInjected",
  9542. "/a\nInjected",
  9543. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9544. "/a b",
  9545. "/a\tb",
  9546. "/a\x7f",
  9547. };
  9548. for (const auto &evil : evil_targets) {
  9549. detail::BufferStream strm;
  9550. auto n = detail::write_request_line(strm, "GET", evil);
  9551. EXPECT_LT(n, 0);
  9552. EXPECT_TRUE(strm.get_buffer().empty());
  9553. }
  9554. }
  9555. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9556. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9557. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9558. // target reaches write_request. The client must fail cleanly with
  9559. // Error::Write instead of putting a request-line-less, header-injecting
  9560. // request on the wire.
  9561. Server svr;
  9562. svr.Get("/a", [](const Request &, Response &res) {
  9563. res.set_content("ok", "text/plain");
  9564. });
  9565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. thread.join();
  9569. ASSERT_FALSE(svr.is_running());
  9570. });
  9571. svr.wait_until_ready();
  9572. {
  9573. Client cli(HOST, PORT);
  9574. cli.set_path_encode(false);
  9575. // The request is rejected before anything is written, so the connection
  9576. // stays silent and the subsequent response read would otherwise block for
  9577. // the full default read timeout. Shorten it -- the assertion is on the
  9578. // error, not the timeout.
  9579. cli.set_read_timeout(1, 0);
  9580. auto res = cli.Get("/a\r\nInjected: pwned");
  9581. EXPECT_FALSE(res);
  9582. EXPECT_EQ(Error::Write, res.error());
  9583. }
  9584. }
  9585. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9586. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9587. // including extension methods.
  9588. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9589. for (const auto &method : good_methods) {
  9590. detail::BufferStream strm;
  9591. auto n = detail::write_request_line(strm, method, "/");
  9592. EXPECT_GT(n, 0);
  9593. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9594. }
  9595. // A method carrying CR/LF would split the request line and smuggle a whole
  9596. // request ahead of the real one. A space or an empty method corrupts the
  9597. // request line. All must be rejected before anything reaches the wire.
  9598. const std::string evil_methods[] = {
  9599. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9600. "GET\r\nInjected: pwned",
  9601. "GET\r",
  9602. "GET\n",
  9603. "GE T",
  9604. "",
  9605. };
  9606. for (const auto &evil : evil_methods) {
  9607. detail::BufferStream strm;
  9608. auto n = detail::write_request_line(strm, evil, "/");
  9609. EXPECT_LT(n, 0);
  9610. EXPECT_TRUE(strm.get_buffer().empty());
  9611. }
  9612. }
  9613. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9614. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9615. // through Client::send must fail with Error::Write and no request, neither
  9616. // the smuggled one nor the real one, may reach the server.
  9617. Server svr;
  9618. std::atomic<int> request_count(0);
  9619. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9620. request_count++;
  9621. res.status = StatusCode::OK_200;
  9622. return Server::HandlerResponse::Handled;
  9623. });
  9624. auto port = svr.bind_to_any_port(HOST);
  9625. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9626. auto se = detail::scope_exit([&] {
  9627. svr.stop();
  9628. thread.join();
  9629. ASSERT_FALSE(svr.is_running());
  9630. });
  9631. svr.wait_until_ready();
  9632. {
  9633. Client cli(HOST, port);
  9634. const std::string evil_methods[] = {
  9635. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9636. "GE T",
  9637. "",
  9638. };
  9639. for (const auto &evil : evil_methods) {
  9640. Request req;
  9641. req.method = evil;
  9642. req.path = "/";
  9643. auto res = cli.send(req);
  9644. EXPECT_FALSE(res);
  9645. EXPECT_EQ(Error::Write, res.error());
  9646. }
  9647. auto handle =
  9648. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9649. EXPECT_FALSE(handle.is_valid());
  9650. EXPECT_EQ(Error::Write, handle.error);
  9651. // A valid request on the same client still goes through.
  9652. auto res = cli.Get("/");
  9653. ASSERT_TRUE(res);
  9654. EXPECT_EQ(StatusCode::OK_200, res->status);
  9655. }
  9656. EXPECT_EQ(1, request_count.load());
  9657. }
  9658. // Sends a raw request and verifies that there isn't a crash or exception.
  9659. static void test_raw_request(const std::string &req,
  9660. std::string *out = nullptr) {
  9661. Server svr;
  9662. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9663. res.set_content("ok", "text/plain");
  9664. });
  9665. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Get("/header_field_value_check",
  9669. [&](const Request & /*req*/, Response &res) {
  9670. res.set_content("ok", "text/plain");
  9671. });
  9672. svr.CustomRoute("PROPFIND", "/dav",
  9673. [&](const Request & /*req*/, Response &res) {
  9674. res.status = StatusCode::MultiStatus_207;
  9675. });
  9676. // Server read timeout must be longer than the client read timeout for the
  9677. // bug to reproduce, probably to force the server to process a request
  9678. // without a trailing blank line.
  9679. const time_t client_read_timeout_sec = 1;
  9680. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9681. bool listen_thread_ok = false;
  9682. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. t.join();
  9686. ASSERT_FALSE(svr.is_running());
  9687. EXPECT_TRUE(listen_thread_ok);
  9688. });
  9689. svr.wait_until_ready();
  9690. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9691. }
  9692. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9693. // A certain header line causes an exception if the header property is parsed
  9694. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9695. test_raw_request(
  9696. "GET /hi HTTP/1.1\r\n"
  9697. " : "
  9698. " "
  9699. " ");
  9700. }
  9701. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9702. // A certain header line causes an exception if the header property *name* is
  9703. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9704. // greedy matcher and requires backtracking when there are a lot of ":"
  9705. // characters.
  9706. // This occurs with libc++ but not libstdc++.
  9707. test_raw_request(
  9708. "GET /hi HTTP/1.1\r\n"
  9709. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9710. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9711. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9712. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9713. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9714. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9715. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9716. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9717. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9718. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9719. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9720. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9721. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9722. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9723. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9724. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9725. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9726. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9727. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9728. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9729. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9730. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9731. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9732. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9733. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9734. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9735. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9736. "&&&%%%");
  9737. }
  9738. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9739. // Make sure this doesn't crash the server.
  9740. // In a previous version of the header line regex, the "\r" rendered the line
  9741. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9742. // a new position where the leading white space ended and the field value
  9743. // began.
  9744. // The crash occurs with libc++ but not libstdc++.
  9745. test_raw_request("GET /hi HTTP/1.1\r\n"
  9746. "a:" +
  9747. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9748. "\r\n"
  9749. "\r\n");
  9750. }
  9751. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9752. const char *rejected[] = {
  9753. // RFC 9112 §3: one SP between the parts, and nothing else
  9754. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9755. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9756. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9757. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9758. // A request-target has no fragment
  9759. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. // An HTTP/1.1 request needs a Host
  9761. "GET /hi HTTP/1.1\r\n\r\n",
  9762. };
  9763. for (auto request : rejected) {
  9764. std::string out;
  9765. test_raw_request(request, &out);
  9766. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9767. }
  9768. std::string out;
  9769. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9770. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9771. }
  9772. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9773. // RFC 9112 §6.1
  9774. const char *requests[] = {
  9775. "PUT /put_hi HTTP/1.1\r\n"
  9776. "Host: localhost\r\n"
  9777. "Content-Length: 0\r\n"
  9778. "Transfer-Encoding: chunked\r\n"
  9779. "\r\n"
  9780. "0\r\n\r\n",
  9781. "PUT /put_hi HTTP/1.0\r\n"
  9782. "Connection: keep-alive\r\n"
  9783. "Transfer-Encoding: chunked\r\n"
  9784. "\r\n"
  9785. "0\r\n\r\n",
  9786. };
  9787. for (auto request : requests) {
  9788. std::string out;
  9789. test_raw_request(request, &out);
  9790. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9791. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9792. }
  9793. }
  9794. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9795. std::string out;
  9796. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9797. "Content-Type: text/plain\r\n"
  9798. "Transfer-Encoding: chunked\r\n"
  9799. "\r\n"
  9800. "nothex\r\n",
  9801. &out);
  9802. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9803. }
  9804. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9805. std::string out;
  9806. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9807. "Content-Type: text/plain\r\n"
  9808. "Transfer-Encoding: chunked\r\n"
  9809. "\r\n"
  9810. "3\r\n"
  9811. "xyz\r\n"
  9812. "NaN\r\n",
  9813. &out);
  9814. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9815. }
  9816. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9817. std::string out;
  9818. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9819. "Content-Type: text/plain\r\n"
  9820. "Transfer-Encoding: chunked\r\n"
  9821. "\r\n"
  9822. // Length is too large for 64 bits.
  9823. "1ffffffffffffffff\r\n"
  9824. "xyz\r\n",
  9825. &out);
  9826. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9827. }
  9828. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9829. test_raw_request("GET /hi HTTP/1.1\r\n"
  9830. "Content-Type: text/plain\r\n\r");
  9831. }
  9832. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9833. std::string out;
  9834. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9835. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9836. }
  9837. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9838. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9839. std::string out;
  9840. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9841. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9842. }
  9843. }
  9844. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9845. std::string out;
  9846. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9847. "Host: localhost\r\n"
  9848. "Connection: close\r\n\r\n",
  9849. &out);
  9850. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9851. }
  9852. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9853. Server svr;
  9854. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9855. EXPECT_TRUE(!req.remote_addr.empty());
  9856. });
  9857. thread t = thread([&] { svr.listen(HOST, PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. t.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.wait_until_ready();
  9864. // Send an invalid request line to trigger Bad Request
  9865. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9866. std::string out;
  9867. ASSERT_TRUE(send_request(5, bad_req, &out));
  9868. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9869. }
  9870. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9871. // answered right away rather than blocking on a read that waits for EOF.
  9872. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9873. std::string out;
  9874. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9875. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9876. }
  9877. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9878. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9879. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9880. for (const auto *method : methods) {
  9881. Server svr;
  9882. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9883. EXPECT_FALSE(svr.is_valid()) << method;
  9884. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9885. }
  9886. }
  9887. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9888. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9889. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9890. for (const auto *method : methods) {
  9891. Server svr;
  9892. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9893. EXPECT_FALSE(svr.is_valid()) << method;
  9894. }
  9895. }
  9896. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9897. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9898. "COPY", "MOVE", "LOCK",
  9899. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9900. Server svr;
  9901. for (const auto *method : methods) {
  9902. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9903. }
  9904. EXPECT_TRUE(svr.is_valid());
  9905. }
  9906. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9907. Server svr;
  9908. svr.CustomRoute("POST", "/x",
  9909. [](const Request &, Response &, const ContentReader &) {});
  9910. EXPECT_FALSE(svr.is_valid());
  9911. }
  9912. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9913. Server svr;
  9914. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9915. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9916. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9917. EXPECT_FALSE(svr.is_valid());
  9918. }
  9919. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9920. Server svr;
  9921. auto captured = Error::Success;
  9922. svr.set_error_logger(
  9923. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9924. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9925. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9926. }
  9927. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9928. std::string out;
  9929. std::string request(
  9930. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9931. test_raw_request(request, &out);
  9932. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9933. }
  9934. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9935. std::string out;
  9936. std::string request(
  9937. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9938. test_raw_request(request, &out);
  9939. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9940. }
  9941. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9942. std::string out;
  9943. std::string request(
  9944. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9945. test_raw_request(request, &out);
  9946. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9947. }
  9948. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9949. std::string out;
  9950. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9951. "Host: localhost\r\n"
  9952. "Test: \r\n\r\n",
  9953. &out);
  9954. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9955. }
  9956. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9957. Server svr;
  9958. std::string x_custom;
  9959. std::string cookie;
  9960. std::string xff;
  9961. std::string x_unicode;
  9962. std::string x_iis;
  9963. svr.Get("/check", [&](const Request &req, Response &res) {
  9964. x_custom = req.get_header_value("X-Custom");
  9965. cookie = req.get_header_value("Cookie");
  9966. xff = req.get_header_value("X-Forwarded-For");
  9967. x_unicode = req.get_header_value("X-Unicode");
  9968. x_iis = req.get_header_value("X-IIS");
  9969. res.set_content("ok", "text/plain");
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. });
  9977. svr.wait_until_ready();
  9978. const std::string req = "GET /check HTTP/1.1\r\n"
  9979. "Host: localhost\r\n"
  9980. "X-Custom: a%0D%0AInjected: b\r\n"
  9981. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9982. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9983. "X-Unicode: %E3%81%82\r\n"
  9984. "X-IIS: %u00E9\r\n"
  9985. "Connection: close\r\n"
  9986. "\r\n";
  9987. std::string res;
  9988. ASSERT_TRUE(send_request(5, req, &res));
  9989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9990. // Every value must be returned verbatim (wire form), with no decoding.
  9991. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9992. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9993. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9994. EXPECT_EQ("%E3%81%82", x_unicode);
  9995. EXPECT_EQ("%u00E9", x_iis);
  9996. }
  9997. // Applications that previously relied on automatic percent-decoding can
  9998. // reproduce the old behavior by explicitly calling decode_path_component()
  9999. // or, for RFC 3986 conformance, decode_uri_component().
  10000. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10001. Server svr;
  10002. std::string decoded;
  10003. svr.Get("/check", [&](const Request &req, Response &res) {
  10004. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10005. res.set_content("ok", "text/plain");
  10006. });
  10007. thread t = thread([&] { svr.listen(HOST, PORT); });
  10008. auto se = detail::scope_exit([&] {
  10009. svr.stop();
  10010. t.join();
  10011. ASSERT_FALSE(svr.is_running());
  10012. });
  10013. svr.wait_until_ready();
  10014. const std::string req = "GET /check HTTP/1.1\r\n"
  10015. "Host: localhost\r\n"
  10016. "X-Custom: hello%20world\r\n"
  10017. "Connection: close\r\n"
  10018. "\r\n";
  10019. std::string res;
  10020. ASSERT_TRUE(send_request(5, req, &res));
  10021. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10022. EXPECT_EQ("hello world", decoded);
  10023. }
  10024. // Regression test for #2033. Browsers send Referer values that include
  10025. // percent-encoded characters such as %0A inside the URL. Decoding the
  10026. // header value would either trip the post-decode CR/LF/NUL guard (the
  10027. // original bug, returning 400) or, after that guard was relaxed, silently
  10028. // store a literal LF — both unacceptable. The wire form must round-trip.
  10029. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10030. Server svr;
  10031. std::string referer;
  10032. svr.Get("/check", [&](const Request &req, Response &res) {
  10033. referer = req.get_header_value("Referer");
  10034. res.set_content("ok", "text/plain");
  10035. });
  10036. thread t = thread([&] { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. const std::string req = "GET /check HTTP/1.1\r\n"
  10044. "Host: localhost\r\n"
  10045. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10046. "Connection: close\r\n"
  10047. "\r\n";
  10048. std::string res;
  10049. ASSERT_TRUE(send_request(5, req, &res));
  10050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10051. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10052. }
  10053. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10054. Server svr;
  10055. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10056. res.set_header("Cache-Control", "no-cache");
  10057. res.set_chunked_content_provider(
  10058. "text/event-stream", [](size_t offset, DataSink &sink) {
  10059. std::string s = "data:";
  10060. s += std::to_string(offset);
  10061. s += "\n\n";
  10062. auto ret = sink.write(s.data(), s.size());
  10063. EXPECT_TRUE(ret);
  10064. std::this_thread::sleep_for(std::chrono::seconds(1));
  10065. return true;
  10066. });
  10067. });
  10068. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10069. svr.wait_until_ready();
  10070. Client client(HOST, PORT);
  10071. const Headers headers = {{"Accept", "text/event-stream"}};
  10072. auto get_thread = std::thread([&client, &headers]() {
  10073. auto res = client.Get(
  10074. "/events", headers,
  10075. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10076. });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. get_thread.join();
  10080. listen_thread.join();
  10081. ASSERT_FALSE(svr.is_running());
  10082. });
  10083. // Give GET time to get a few messages.
  10084. std::this_thread::sleep_for(std::chrono::seconds(2));
  10085. }
  10086. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10087. httplib::Server svr;
  10088. svr.Post("/hi",
  10089. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10090. res.status = StatusCode::OK_200;
  10091. });
  10092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10093. svr.wait_until_ready();
  10094. Client cli(HOST, PORT);
  10095. auto res = cli.Post("/hi", "data", "text/plain");
  10096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10097. EXPECT_EQ(StatusCode::OK_200, res->status);
  10098. svr.stop();
  10099. thread.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. res = cli.Post("/hi", "data", "text/plain");
  10102. ASSERT_FALSE(res);
  10103. }
  10104. TEST(ServerStopTest, ListenFailure) {
  10105. Server svr;
  10106. auto t = thread([&]() {
  10107. auto ret = svr.listen("????", PORT);
  10108. EXPECT_FALSE(ret);
  10109. });
  10110. svr.wait_until_ready();
  10111. svr.stop();
  10112. t.join();
  10113. }
  10114. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10115. TEST(ServerStopTest, Decommision) {
  10116. Server svr;
  10117. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10118. for (int i = 0; i < 4; i++) {
  10119. auto is_even = !(i % 2);
  10120. std::thread t{[&] {
  10121. try {
  10122. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10123. if (is_even) {
  10124. throw std::runtime_error("Some thing that happens to go wrong.");
  10125. }
  10126. svr.listen(HOST, PORT);
  10127. } catch (...) { svr.decommission(); }
  10128. }};
  10129. svr.wait_until_ready();
  10130. // Server is up
  10131. {
  10132. Client cli(HOST, PORT);
  10133. auto res = cli.Get("/hi");
  10134. if (is_even) {
  10135. EXPECT_FALSE(res);
  10136. } else {
  10137. EXPECT_TRUE(res);
  10138. EXPECT_EQ("hi...", res->body);
  10139. }
  10140. }
  10141. svr.stop();
  10142. t.join();
  10143. // Server is down...
  10144. {
  10145. Client cli(HOST, PORT);
  10146. auto res = cli.Get("/hi");
  10147. EXPECT_FALSE(res);
  10148. }
  10149. }
  10150. }
  10151. #endif
  10152. // Helper function for string body upload progress tests
  10153. template <typename SetupHandler, typename ClientCall>
  10154. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10155. ClientCall &&client_call,
  10156. const string &body) {
  10157. Server svr;
  10158. setup_handler(svr);
  10159. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. t.join();
  10163. });
  10164. svr.wait_until_ready();
  10165. Client cli(HOST, PORT);
  10166. vector<uint64_t> progress_values;
  10167. bool progress_called = false;
  10168. auto res =
  10169. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10170. progress_values.push_back(current);
  10171. progress_called = true;
  10172. return true;
  10173. });
  10174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10175. EXPECT_EQ(200, res->status);
  10176. EXPECT_TRUE(progress_called);
  10177. }
  10178. TEST(UploadProgressTest, PostStringBodyBasic) {
  10179. TestStringBodyUploadProgress(
  10180. [](Server &svr) {
  10181. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10182. res.set_content("received", "text/plain");
  10183. });
  10184. },
  10185. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10186. return cli.Post("/test", body, "text/plain", progress_callback);
  10187. },
  10188. "test data for upload progress");
  10189. }
  10190. TEST(UploadProgressTest, PutStringBodyBasic) {
  10191. TestStringBodyUploadProgress(
  10192. [](Server &svr) {
  10193. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10194. res.set_content("put received", "text/plain");
  10195. });
  10196. },
  10197. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10198. return cli.Put("/test", body, "text/plain", progress_callback);
  10199. },
  10200. "put test data for upload progress");
  10201. }
  10202. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10203. TestStringBodyUploadProgress(
  10204. [](Server &svr) {
  10205. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10206. res.set_content("patch received", "text/plain");
  10207. });
  10208. },
  10209. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10210. return cli.Patch("/test", body, "text/plain", progress_callback);
  10211. },
  10212. "patch test data for upload progress");
  10213. }
  10214. // Helper function for content provider upload progress tests
  10215. template <typename SetupHandler, typename ClientCall>
  10216. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10217. ClientCall &&client_call) {
  10218. Server svr;
  10219. setup_handler(svr);
  10220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. t.join();
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, PORT);
  10227. vector<uint64_t> progress_values;
  10228. auto res =
  10229. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10230. progress_values.push_back(current);
  10231. return true;
  10232. });
  10233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10234. EXPECT_EQ(200, res->status);
  10235. EXPECT_FALSE(progress_values.empty());
  10236. }
  10237. TEST(UploadProgressTest, PostContentProviderProgress) {
  10238. TestContentProviderUploadProgress(
  10239. [](Server &svr) {
  10240. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10241. res.set_content("provider received", "text/plain");
  10242. });
  10243. },
  10244. [](Client &cli, UploadProgress progress_callback) {
  10245. return cli.Post(
  10246. "/test", 9,
  10247. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10248. sink.os << "test data";
  10249. return true;
  10250. },
  10251. "text/plain", progress_callback);
  10252. });
  10253. }
  10254. // Helper function for multipart upload progress tests
  10255. template <typename SetupHandler, typename ClientCall>
  10256. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10257. ClientCall &&client_call,
  10258. const string &endpoint) {
  10259. Server svr;
  10260. setup_handler(svr);
  10261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10262. auto se = detail::scope_exit([&] {
  10263. svr.stop();
  10264. t.join();
  10265. });
  10266. svr.wait_until_ready();
  10267. Client cli(HOST, PORT);
  10268. vector<uint64_t> progress_values;
  10269. UploadFormDataItems items = {
  10270. {"field1", "value1", "", ""},
  10271. {"field2", "longer value for progress tracking test", "", ""},
  10272. {"file1", "file content data for upload progress", "test.txt",
  10273. "text/plain"}};
  10274. auto res = client_call(cli, endpoint, items,
  10275. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10276. progress_values.push_back(current);
  10277. return true;
  10278. });
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(200, res->status);
  10281. EXPECT_FALSE(progress_values.empty());
  10282. }
  10283. TEST(UploadProgressTest, PostMultipartProgress) {
  10284. TestMultipartUploadProgress(
  10285. [](Server &svr) {
  10286. svr.Post("/multipart", [](const Request &req, Response &res) {
  10287. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10288. res.set_content("multipart received", "text/plain");
  10289. });
  10290. },
  10291. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10292. UploadProgress progress_callback) {
  10293. return cli.Post(endpoint, items, progress_callback);
  10294. },
  10295. "/multipart");
  10296. }
  10297. // Helper function for basic download progress tests
  10298. template <typename SetupHandler, typename ClientCall>
  10299. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10300. ClientCall &&client_call, const string &endpoint,
  10301. size_t expected_content_size) {
  10302. Server svr;
  10303. setup_handler(svr);
  10304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10305. auto se = detail::scope_exit([&] {
  10306. svr.stop();
  10307. t.join();
  10308. });
  10309. svr.wait_until_ready();
  10310. Client cli(HOST, PORT);
  10311. vector<uint64_t> progress_values;
  10312. auto res = client_call(cli, endpoint,
  10313. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10314. progress_values.push_back(current);
  10315. return true;
  10316. });
  10317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10318. EXPECT_EQ(200, res->status);
  10319. EXPECT_FALSE(progress_values.empty());
  10320. EXPECT_EQ(expected_content_size, res->body.size());
  10321. }
  10322. TEST(DownloadProgressTest, GetBasic) {
  10323. TestBasicDownloadProgress(
  10324. [](Server &svr) {
  10325. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10326. string content(1000, 'D');
  10327. res.set_content(content, "text/plain");
  10328. });
  10329. },
  10330. [](Client &cli, const string &endpoint,
  10331. DownloadProgress progress_callback) {
  10332. return cli.Get(endpoint, progress_callback);
  10333. },
  10334. "/download", 1000u);
  10335. }
  10336. // Helper function for content receiver download progress tests
  10337. template <typename SetupHandler, typename ClientCall>
  10338. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10339. ClientCall &&client_call,
  10340. const string &endpoint,
  10341. size_t expected_content_size) {
  10342. Server svr;
  10343. setup_handler(svr);
  10344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. });
  10349. svr.wait_until_ready();
  10350. Client cli(HOST, PORT);
  10351. vector<uint64_t> progress_values;
  10352. string received_body;
  10353. auto res = client_call(
  10354. cli, endpoint,
  10355. [&](const char *data, size_t data_length) -> bool {
  10356. received_body.append(data, data_length);
  10357. return true;
  10358. },
  10359. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10360. progress_values.push_back(current);
  10361. return true;
  10362. });
  10363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10364. EXPECT_EQ(200, res->status);
  10365. EXPECT_FALSE(progress_values.empty());
  10366. EXPECT_EQ(expected_content_size, received_body.size());
  10367. EXPECT_TRUE(res->body.empty());
  10368. }
  10369. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10370. TestContentReceiverDownloadProgress(
  10371. [](Server &svr) {
  10372. svr.Get("/download-receiver",
  10373. [](const Request & /*req*/, Response &res) {
  10374. string content(2000, 'R');
  10375. res.set_content(content, "text/plain");
  10376. });
  10377. },
  10378. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10379. DownloadProgress progress_callback) {
  10380. return cli.Get(endpoint, content_receiver, progress_callback);
  10381. },
  10382. "/download-receiver", 2000u);
  10383. }
  10384. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10385. // A provider reaching a pass with nothing to hand over - an empty buffer
  10386. // popped off a queue, say - must not be taken to mean the body is finished.
  10387. // It used to end the loop with the terminating chunk unwritten while the
  10388. // server still considered the response complete, so the peer waited for an
  10389. // end that never arrived.
  10390. Server svr;
  10391. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10392. auto step = std::make_shared<int>(0);
  10393. res.set_chunked_content_provider("text/plain",
  10394. [step](size_t /*offset*/, DataSink &sink) {
  10395. switch ((*step)++) {
  10396. case 0: sink.write("", 0); break;
  10397. case 1: sink.write("hello", 5); break;
  10398. default: sink.done(); break;
  10399. }
  10400. return true;
  10401. });
  10402. });
  10403. auto port = svr.bind_to_any_port(HOST);
  10404. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10405. auto listen_se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. listen_thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, port);
  10412. // Without the fix the body is never terminated, so bound the wait rather
  10413. // than letting the test hang on the default read timeout.
  10414. cli.set_read_timeout(5, 0);
  10415. auto res = cli.Get("/stream");
  10416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10417. EXPECT_EQ(StatusCode::OK_200, res->status);
  10418. EXPECT_EQ("hello", res->body);
  10419. }
  10420. TEST(StreamingTest, NoContentLengthStreaming) {
  10421. Server svr;
  10422. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10423. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10424. if (offset < 6) {
  10425. sink.os << (offset < 3 ? "a" : "b");
  10426. } else {
  10427. sink.done();
  10428. }
  10429. return true;
  10430. });
  10431. });
  10432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10433. auto listen_se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. listen_thread.join();
  10436. ASSERT_FALSE(svr.is_running());
  10437. });
  10438. svr.wait_until_ready();
  10439. Client client(HOST, PORT);
  10440. auto get_thread = std::thread([&client]() {
  10441. std::string s;
  10442. auto res =
  10443. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10444. s += std::string(data, len);
  10445. return true;
  10446. });
  10447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10448. EXPECT_EQ(StatusCode::OK_200, res->status);
  10449. EXPECT_EQ("aaabbb", s);
  10450. });
  10451. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10452. // Give GET time to get a few messages.
  10453. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10454. }
  10455. TEST(MountTest, Unmount) {
  10456. Server svr;
  10457. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10458. auto se = detail::scope_exit([&] {
  10459. svr.stop();
  10460. listen_thread.join();
  10461. ASSERT_FALSE(svr.is_running());
  10462. });
  10463. svr.wait_until_ready();
  10464. Client cli("localhost", PORT);
  10465. svr.set_mount_point("/mount2", "./www2");
  10466. auto res = cli.Get("/");
  10467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10469. res = cli.Get("/mount2/dir/test.html");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::OK_200, res->status);
  10472. svr.set_mount_point("/", "./www");
  10473. res = cli.Get("/dir/");
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. EXPECT_EQ(StatusCode::OK_200, res->status);
  10476. svr.remove_mount_point("/");
  10477. res = cli.Get("/dir/");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10480. svr.remove_mount_point("/mount2");
  10481. res = cli.Get("/mount2/dir/test.html");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10484. }
  10485. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10486. Server svr;
  10487. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10488. svr.Get("/api/hello", [](const Request &, Response &res) {
  10489. res.set_content("api", "text/plain");
  10490. });
  10491. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10492. auto se = detail::scope_exit([&] {
  10493. svr.stop();
  10494. listen_thread.join();
  10495. ASSERT_FALSE(svr.is_running());
  10496. });
  10497. svr.wait_until_ready();
  10498. Client cli(HOST, PORT);
  10499. auto res = cli.Get("/dir/test.html");
  10500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10501. EXPECT_EQ(StatusCode::OK_200, res->status);
  10502. res = cli.Get("/api/hello");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. EXPECT_EQ("api", res->body);
  10506. }
  10507. TEST(MountTest, PathSegmentBoundary) {
  10508. Server svr;
  10509. svr.set_mount_point("/mount2", "./www2");
  10510. svr.set_mount_point("/", "./www");
  10511. auto port = svr.bind_to_any_port(HOST);
  10512. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10513. auto se = detail::scope_exit([&] {
  10514. svr.stop();
  10515. listen_thread.join();
  10516. ASSERT_FALSE(svr.is_running());
  10517. });
  10518. svr.wait_until_ready();
  10519. Client cli(HOST, port);
  10520. auto res = cli.Get("/mount2/dir/test.html");
  10521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10522. EXPECT_EQ(StatusCode::OK_200, res->status);
  10523. // "/mount2" must not match part-way through a path segment.
  10524. res = cli.Get("/mount2dir/test.html");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10527. // A mount point ending in '/' keeps matching every path below it.
  10528. res = cli.Get("/dir/test.html");
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(StatusCode::OK_200, res->status);
  10531. }
  10532. TEST(MountTest, Redicect) {
  10533. Server svr;
  10534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10535. auto se = detail::scope_exit([&] {
  10536. svr.stop();
  10537. listen_thread.join();
  10538. ASSERT_FALSE(svr.is_running());
  10539. });
  10540. svr.set_mount_point("/", "./www");
  10541. svr.wait_until_ready();
  10542. Client cli("localhost", PORT);
  10543. auto res = cli.Get("/dir/");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::OK_200, res->status);
  10546. res = cli.Get("/dir");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10549. res = cli.Get("/file");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::OK_200, res->status);
  10552. res = cli.Get("/file/");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10555. cli.set_follow_location(true);
  10556. res = cli.Get("/dir");
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(StatusCode::OK_200, res->status);
  10559. }
  10560. TEST(MountTest, MultibytesPathName) {
  10561. Server svr;
  10562. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. listen_thread.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.set_mount_point("/", "./www");
  10569. svr.wait_until_ready();
  10570. Client cli("localhost", PORT);
  10571. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10573. EXPECT_EQ(StatusCode::OK_200, res->status);
  10574. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10575. }
  10576. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10577. // in the pre-routing handler sees the path of every file that is served
  10578. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10579. Server svr;
  10580. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10581. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10582. if (req.path == "/dir/test.html") {
  10583. res.status = StatusCode::Unauthorized_401;
  10584. return Server::HandlerResponse::Handled;
  10585. }
  10586. return Server::HandlerResponse::Unhandled;
  10587. });
  10588. auto port = svr.bind_to_any_port(HOST);
  10589. ASSERT_LT(0, port);
  10590. thread t = thread([&] { svr.listen_after_bind(); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. t.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli(HOST, port);
  10598. for (auto path :
  10599. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10600. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10601. SCOPED_TRACE(path);
  10602. auto res = cli.Get(path);
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10605. }
  10606. }
  10607. #ifdef _WIN32
  10608. // Issue #2435: mmap::open() must succeed even when another handle holds
  10609. // the file open for writing (e.g. an active log file).
  10610. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10611. const char *path = "mmap_concurrent_writer_test.txt";
  10612. const char *content = "hello";
  10613. {
  10614. std::ofstream f(path, std::ios::binary);
  10615. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10616. }
  10617. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10618. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10619. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10620. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10621. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10622. detail::mmap m(path);
  10623. ASSERT_TRUE(m.is_open());
  10624. EXPECT_EQ(strlen(content), m.size());
  10625. char buf[8];
  10626. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10627. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10628. }
  10629. #endif
  10630. #ifndef _WIN32
  10631. // A directory or a device has no size to serve.
  10632. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10633. const char *path = "./mmap_not_regular_test_dir";
  10634. ASSERT_EQ(0, ::mkdir(path, 0755));
  10635. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10636. for (auto p : {path, "/dev/null"}) {
  10637. detail::mmap m(p);
  10638. EXPECT_FALSE(m.is_open()) << p;
  10639. EXPECT_EQ(0U, m.size()) << p;
  10640. }
  10641. Server svr;
  10642. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10643. res.set_file_content("/dev/null");
  10644. });
  10645. auto port = svr.bind_to_any_port(HOST);
  10646. thread t = thread([&] { svr.listen_after_bind(); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. t.join();
  10650. });
  10651. svr.wait_until_ready();
  10652. auto res = Client(HOST, port).Get("/null");
  10653. ASSERT_TRUE(res);
  10654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10655. }
  10656. #endif
  10657. #ifdef __linux__
  10658. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10659. TEST(MmapTest, FileIsNotMapped) {
  10660. const char *path = "mmap_not_mapped_test.txt";
  10661. {
  10662. std::ofstream f(path, std::ios::binary);
  10663. f << "hello";
  10664. }
  10665. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10666. detail::mmap m(path);
  10667. ASSERT_TRUE(m.is_open());
  10668. std::ifstream maps("/proc/self/maps");
  10669. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10670. std::istreambuf_iterator<char>());
  10671. EXPECT_EQ(std::string::npos, mappings.find(path));
  10672. }
  10673. #endif
  10674. TEST(KeepAliveTest, ReadTimeout) {
  10675. Server svr;
  10676. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10677. std::this_thread::sleep_for(std::chrono::seconds(2));
  10678. res.set_content("a", "text/plain");
  10679. });
  10680. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10681. res.set_content("b", "text/plain");
  10682. });
  10683. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10684. auto se = detail::scope_exit([&] {
  10685. svr.stop();
  10686. listen_thread.join();
  10687. ASSERT_FALSE(svr.is_running());
  10688. });
  10689. svr.wait_until_ready();
  10690. Client cli("localhost", PORT);
  10691. cli.set_keep_alive(true);
  10692. cli.set_read_timeout(std::chrono::seconds(1));
  10693. auto resa = cli.Get("/a");
  10694. ASSERT_FALSE(resa);
  10695. EXPECT_EQ(Error::Read, resa.error());
  10696. auto resb = cli.Get("/b");
  10697. ASSERT_TRUE(resb);
  10698. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10699. EXPECT_EQ("b", resb->body);
  10700. }
  10701. TEST(KeepAliveTest, MaxCount) {
  10702. size_t keep_alive_max_count = 3;
  10703. Server svr;
  10704. svr.set_keep_alive_max_count(keep_alive_max_count);
  10705. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10706. res.set_content("Hello World!", "text/plain");
  10707. });
  10708. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10709. auto se = detail::scope_exit([&] {
  10710. svr.stop();
  10711. listen_thread.join();
  10712. ASSERT_FALSE(svr.is_running());
  10713. });
  10714. svr.wait_until_ready();
  10715. Client cli(HOST, PORT);
  10716. cli.set_keep_alive(true);
  10717. for (size_t i = 0; i < 5; i++) {
  10718. auto result = cli.Get("/hi");
  10719. ASSERT_TRUE(result);
  10720. EXPECT_EQ(StatusCode::OK_200, result->status);
  10721. if (i == keep_alive_max_count - 1) {
  10722. EXPECT_EQ("close", result->get_header_value("Connection"));
  10723. } else {
  10724. EXPECT_FALSE(result->has_header("Connection"));
  10725. }
  10726. }
  10727. }
  10728. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10729. // can pull the next one into the server's buffer. The server must serve it
  10730. // without waiting for the socket to become readable again. The keep-alive
  10731. // timeout outlasts the client's read timeout, so a request left waiting for it
  10732. // shows up as a missing response.
  10733. static void serve_pipelining_routes(Server &svr,
  10734. const std::function<void(int)> &client) {
  10735. svr.set_keep_alive_timeout(5);
  10736. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10737. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10738. });
  10739. svr.Post("/echo", [](const Request &req, Response &res) {
  10740. res.set_content("echo " + req.body, "text/plain");
  10741. });
  10742. auto port = svr.bind_to_any_port(HOST);
  10743. thread t = thread([&] { svr.listen_after_bind(); });
  10744. auto se = detail::scope_exit([&] {
  10745. svr.stop();
  10746. t.join();
  10747. });
  10748. svr.wait_until_ready();
  10749. client(port);
  10750. }
  10751. static std::string
  10752. send_pipelined_requests(const std::vector<std::string> &parts) {
  10753. Server svr;
  10754. std::string res;
  10755. serve_pipelining_routes(svr, [&](int port) {
  10756. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10757. });
  10758. return res;
  10759. }
  10760. static void expect_in_order(const std::string &res,
  10761. const std::vector<std::string> &bodies) {
  10762. size_t pos = 0;
  10763. for (const auto &body : bodies) {
  10764. pos = res.find(body, pos);
  10765. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10766. pos += body.size();
  10767. }
  10768. }
  10769. TEST(KeepAliveTest, PipelinedRequests) {
  10770. auto res = send_pipelined_requests(
  10771. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10772. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10773. "Content-Length: 4\r\n\r\nbody"
  10774. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10775. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10776. }
  10777. // The second request starts in the server's buffer and ends on the socket.
  10778. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10779. auto res =
  10780. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10781. "GET /hi/2 HTTP/1.1\r\nHo",
  10782. "st: localhost\r\nConnection: close\r\n\r\n"});
  10783. expect_in_order(res, {"hi 1", "hi 2"});
  10784. }
  10785. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10786. // CRLF after a body does not turn into a 400 for the next request.
  10787. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10788. auto res = send_pipelined_requests(
  10789. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10790. "Content-Length: 4\r\n\r\nbody\r\n"
  10791. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10792. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10793. expect_in_order(res, {"echo body", "hi 2"});
  10794. }
  10795. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10796. // must not be served as the next request.
  10797. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10798. auto res = send_pipelined_requests(
  10799. {"INVALID REQUEST LINE\r\n\r\n"
  10800. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10801. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10802. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10803. }
  10804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10805. // Over TLS, the next request is held by the TLS library as already decrypted
  10806. // data rather than on the socket.
  10807. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10809. std::string res;
  10810. serve_pipelining_routes(svr, [&](int port) {
  10811. // One part, so all three requests arrive in one TLS record
  10812. EXPECT_TRUE(send_ssl_request_in_parts(
  10813. 2,
  10814. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10815. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10816. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10817. &res, port));
  10818. });
  10819. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10820. }
  10821. #endif
  10822. TEST(KeepAliveTest, Issue1041) {
  10823. Server svr;
  10824. svr.set_keep_alive_timeout(3);
  10825. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10826. res.set_content("Hello World!", "text/plain");
  10827. });
  10828. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. listen_thread.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. Client cli(HOST, PORT);
  10836. cli.set_keep_alive(true);
  10837. auto result = cli.Get("/hi");
  10838. ASSERT_TRUE(result);
  10839. EXPECT_EQ(StatusCode::OK_200, result->status);
  10840. std::this_thread::sleep_for(std::chrono::seconds(5));
  10841. result = cli.Get("/hi");
  10842. ASSERT_TRUE(result);
  10843. EXPECT_EQ(StatusCode::OK_200, result->status);
  10844. }
  10845. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10846. Server svr;
  10847. svr.set_keep_alive_max_count(0);
  10848. std::set<int> remote_ports;
  10849. svr.Get("/hi", [&](const Request &req, Response &res) {
  10850. remote_ports.insert(req.remote_port);
  10851. res.set_content("hi", "text/plain");
  10852. });
  10853. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10854. auto se = detail::scope_exit([&] {
  10855. svr.stop();
  10856. listen_thread.join();
  10857. ASSERT_FALSE(svr.is_running());
  10858. });
  10859. svr.wait_until_ready();
  10860. Client cli(HOST, PORT);
  10861. cli.set_keep_alive(true);
  10862. for (int i = 0; i < 3; i++) {
  10863. auto res = cli.Get("/hi");
  10864. ASSERT_TRUE(res);
  10865. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10866. }
  10867. // All three over one connection
  10868. EXPECT_EQ(1u, remote_ports.size());
  10869. }
  10870. TEST(KeepAliveTest, Issue1959) {
  10871. Server svr;
  10872. svr.set_keep_alive_timeout(5);
  10873. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10874. res.set_content("a", "text/plain");
  10875. });
  10876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10877. auto se = detail::scope_exit([&] {
  10878. if (!svr.is_running()) return;
  10879. svr.stop();
  10880. listen_thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. Client cli("localhost", PORT);
  10885. cli.set_keep_alive(true);
  10886. using namespace std::chrono;
  10887. auto start = steady_clock::now();
  10888. cli.Get("/a");
  10889. svr.stop();
  10890. listen_thread.join();
  10891. auto end = steady_clock::now();
  10892. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10893. EXPECT_LT(elapsed, 5000);
  10894. }
  10895. #ifdef CPPHTTPLIB_SSL_ENABLED
  10896. TEST(KeepAliveTest, SSLClientReconnection) {
  10897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10898. ASSERT_TRUE(svr.is_valid());
  10899. svr.set_keep_alive_timeout(1);
  10900. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10901. res.set_content("Hello World!", "text/plain");
  10902. });
  10903. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10904. auto se = detail::scope_exit([&] {
  10905. svr.stop();
  10906. listen_thread.join();
  10907. ASSERT_FALSE(svr.is_running());
  10908. });
  10909. svr.wait_until_ready();
  10910. SSLClient cli(HOST, PORT);
  10911. cli.enable_server_certificate_verification(false);
  10912. cli.set_keep_alive(true);
  10913. auto result = cli.Get("/hi");
  10914. ASSERT_TRUE(result);
  10915. EXPECT_EQ(StatusCode::OK_200, result->status);
  10916. result = cli.Get("/hi");
  10917. ASSERT_TRUE(result);
  10918. EXPECT_EQ(StatusCode::OK_200, result->status);
  10919. std::this_thread::sleep_for(std::chrono::seconds(2));
  10920. // Recoonect
  10921. result = cli.Get("/hi");
  10922. ASSERT_TRUE(result);
  10923. EXPECT_EQ(StatusCode::OK_200, result->status);
  10924. result = cli.Get("/hi");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(StatusCode::OK_200, result->status);
  10927. }
  10928. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10930. ASSERT_TRUE(svr.is_valid());
  10931. svr.set_keep_alive_timeout(1);
  10932. std::string content = "reconnect";
  10933. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10934. res.set_content("Hello World!", "text/plain");
  10935. });
  10936. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10937. auto se = detail::scope_exit([&] {
  10938. svr.stop();
  10939. listen_thread.join();
  10940. ASSERT_FALSE(svr.is_running());
  10941. });
  10942. svr.wait_until_ready();
  10943. SSLClient cli(HOST, PORT);
  10944. cli.enable_server_certificate_verification(false);
  10945. cli.set_keep_alive(true);
  10946. auto result = cli.Post(
  10947. "/hi", content.size(),
  10948. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10949. sink.write(content.c_str(), content.size());
  10950. return true;
  10951. },
  10952. "text/plain");
  10953. ASSERT_TRUE(result);
  10954. EXPECT_EQ(200, result->status);
  10955. std::this_thread::sleep_for(std::chrono::seconds(2));
  10956. // Recoonect
  10957. result = cli.Post(
  10958. "/hi", content.size(),
  10959. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10960. sink.write(content.c_str(), content.size());
  10961. return true;
  10962. },
  10963. "text/plain");
  10964. ASSERT_TRUE(result);
  10965. EXPECT_EQ(200, result->status);
  10966. result = cli.Post(
  10967. "/hi", content.size(),
  10968. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10969. sink.write(content.c_str(), content.size());
  10970. return true;
  10971. },
  10972. "text/plain");
  10973. ASSERT_TRUE(result);
  10974. EXPECT_EQ(200, result->status);
  10975. }
  10976. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10977. using namespace httplib::tls;
  10978. {
  10979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10980. ASSERT_TRUE(svr.is_valid());
  10981. svr.Get("/sni", [&](const Request &req, Response &res) {
  10982. std::string expected = req.sni();
  10983. EXPECT_EQ(expected, req.get_param_value("expected"));
  10984. res.set_content("ok", "text/plain");
  10985. });
  10986. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. listen_thread.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. });
  10992. svr.wait_until_ready();
  10993. {
  10994. SSLClient cli("localhost", PORT);
  10995. cli.enable_server_certificate_verification(false);
  10996. auto res = cli.Get("/sni?expected=localhost");
  10997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10998. }
  10999. {
  11000. SSLClient cli("::1", PORT);
  11001. cli.enable_server_certificate_verification(false);
  11002. auto res = cli.Get("/sni?expected=");
  11003. // NOTE: This may fail if the server is listening on IPv4 only
  11004. // (e.g., when localhost resolves to 127.0.0.1 only)
  11005. if (res) {
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. } else {
  11008. EXPECT_EQ(Error::Connection, res.error());
  11009. }
  11010. }
  11011. }
  11012. }
  11013. // The SNI of a failed handshake does not reach the next connection that the
  11014. // same worker thread serves
  11015. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11017. ASSERT_TRUE(svr.is_valid());
  11018. svr.new_task_queue = [] { return new ThreadPool(1); };
  11019. svr.Get("/sni", [](const Request &req, Response &res) {
  11020. res.set_content(req.sni(), "text/plain");
  11021. });
  11022. auto port = svr.bind_to_any_port("127.0.0.1");
  11023. ASSERT_LT(0, port);
  11024. thread t = thread([&] { svr.listen_after_bind(); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. {
  11032. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11033. SSLClient cli("localhost", port);
  11034. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11035. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11036. auto res = cli.Get("/sni");
  11037. ASSERT_FALSE(res);
  11038. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11039. }
  11040. // An IP host sends no SNI (RFC 6066)
  11041. SSLClient cli("127.0.0.1", port);
  11042. cli.enable_server_certificate_verification(false);
  11043. auto res = cli.Get("/sni");
  11044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11045. EXPECT_EQ("", res->body);
  11046. }
  11047. #endif
  11048. TEST(ClientProblemDetectionTest, ContentProvider) {
  11049. Server svr;
  11050. size_t content_length = 1024 * 1024;
  11051. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11052. res.set_content_provider(
  11053. content_length, "text/plain",
  11054. [&](size_t offset, size_t length, DataSink &sink) {
  11055. auto out_len = std::min(length, static_cast<size_t>(1024));
  11056. std::string out(out_len, '@');
  11057. sink.write(out.data(), out_len);
  11058. return offset < 4096;
  11059. },
  11060. [](bool success) { ASSERT_FALSE(success); });
  11061. });
  11062. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11063. res.set_content_provider(
  11064. 0, "text/plain",
  11065. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11066. EXPECT_TRUE(false);
  11067. return true;
  11068. },
  11069. [](bool success) { ASSERT_FALSE(success); });
  11070. });
  11071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. Client cli("localhost", PORT);
  11079. {
  11080. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11081. size_t /*data_length*/) { return false; });
  11082. ASSERT_FALSE(res);
  11083. }
  11084. {
  11085. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11086. size_t /*data_length*/) { return false; });
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. }
  11089. }
  11090. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11091. // A provider that reports success without writing anything and without
  11092. // calling done() used to be handed the same offset and length again on every
  11093. // pass, so it spun for as long as the peer stayed connected.
  11094. Server svr;
  11095. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11096. res.set_content("ok", "text/plain");
  11097. });
  11098. auto port = svr.bind_to_any_port(HOST);
  11099. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11100. auto se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. listen_thread.join();
  11103. ASSERT_FALSE(svr.is_running());
  11104. });
  11105. svr.wait_until_ready();
  11106. std::atomic<int> call_count{0};
  11107. Client cli(HOST, port);
  11108. auto res = cli.Post(
  11109. "/", 1024,
  11110. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11111. // Give up after enough passes to show the spin, so that losing the
  11112. // check below fails this test instead of hanging it.
  11113. return ++call_count < 100;
  11114. },
  11115. "text/plain");
  11116. ASSERT_FALSE(res);
  11117. EXPECT_EQ(Error::Write, res.error());
  11118. EXPECT_EQ(1, call_count.load());
  11119. }
  11120. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11121. // A writer only has to assign `write`. The other three used to be left as
  11122. // empty std::functions, so a provider calling one threw
  11123. // std::bad_function_call out of the thread running it and took the whole
  11124. // process down.
  11125. DataSink sink;
  11126. std::string written;
  11127. sink.write = [&](const char *data, size_t data_len) {
  11128. written.append(data, data_len);
  11129. return true;
  11130. };
  11131. EXPECT_TRUE(sink.is_writable());
  11132. sink.done();
  11133. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11134. EXPECT_TRUE(written.empty());
  11135. }
  11136. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11137. // A sink that cannot carry trailers still has to finish.
  11138. DataSink sink;
  11139. auto done_count = 0;
  11140. sink.done = [&]() { done_count++; };
  11141. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11142. EXPECT_EQ(1, done_count);
  11143. }
  11144. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11145. Server svr;
  11146. const std::string body(4096, 'x');
  11147. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content_provider(body.size(), "text/plain",
  11149. [&](size_t offset, size_t length, DataSink &sink) {
  11150. sink.write(body.data() + offset, length);
  11151. sink.done();
  11152. return true;
  11153. });
  11154. });
  11155. auto port = svr.bind_to_any_port(HOST);
  11156. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli(HOST, port);
  11164. auto res = cli.Get("/");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. EXPECT_EQ(body, res->body);
  11168. }
  11169. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11170. Server svr;
  11171. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11172. res.set_content_provider(
  11173. 1024, "text/plain",
  11174. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11175. sink.write("hello", 5);
  11176. sink.done(); // short of the 1024 bytes the response promised
  11177. return true;
  11178. });
  11179. });
  11180. auto port = svr.bind_to_any_port(HOST);
  11181. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. listen_thread.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. });
  11187. svr.wait_until_ready();
  11188. Client cli(HOST, port);
  11189. cli.set_read_timeout(5, 0);
  11190. // The response is short of its Content-Length, so the client cannot read a
  11191. // complete body. What matters is that this returns at all: a no-op done()
  11192. // would leave the writer looping over a provider that never makes progress.
  11193. auto res = cli.Get("/");
  11194. EXPECT_FALSE(res);
  11195. }
  11196. // Read as the next response by a peer that sees it after a framed body.
  11197. static const std::string smuggled_response =
  11198. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11199. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11200. Server svr;
  11201. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11202. res.set_content_provider(
  11203. 5, "text/plain",
  11204. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11205. auto data = "AAAAA" + smuggled_response;
  11206. sink.write(data.data(), data.size());
  11207. return true;
  11208. });
  11209. });
  11210. thread t = thread([&] { svr.listen(HOST, PORT); });
  11211. auto se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. t.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. });
  11216. svr.wait_until_ready();
  11217. std::string resp;
  11218. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11219. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11220. resp.clear();
  11221. ASSERT_TRUE(send_request(
  11222. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11223. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11224. }
  11225. TEST(NoContentTest, BodyIsNotSent) {
  11226. Server svr;
  11227. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11228. res.status = StatusCode::NoContent_204;
  11229. res.set_content(smuggled_response, "text/plain");
  11230. });
  11231. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11232. res.status = StatusCode::NotModified_304;
  11233. res.set_chunked_content_provider(
  11234. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11235. sink.write(smuggled_response.data(), smuggled_response.size());
  11236. sink.done();
  11237. return true;
  11238. });
  11239. });
  11240. thread t = thread([&] { svr.listen(HOST, PORT); });
  11241. auto se = detail::scope_exit([&] {
  11242. svr.stop();
  11243. t.join();
  11244. ASSERT_FALSE(svr.is_running());
  11245. });
  11246. svr.wait_until_ready();
  11247. for (auto path : {"/204", "/304"}) {
  11248. std::string resp;
  11249. ASSERT_TRUE(send_request(
  11250. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11251. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11252. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11253. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11254. }
  11255. }
  11256. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11257. Server svr;
  11258. std::atomic<bool> smuggled(false);
  11259. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11260. res.set_content("ok", "text/plain");
  11261. });
  11262. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11263. smuggled = true;
  11264. });
  11265. auto port = svr.bind_to_any_port(HOST);
  11266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. listen_thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. // What follows the body would be read as the next request.
  11274. Client cli(HOST, port);
  11275. auto res = cli.Post(
  11276. "/", 5,
  11277. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11278. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11279. sink.write(data.data(), data.size());
  11280. return true;
  11281. },
  11282. "text/plain");
  11283. ASSERT_FALSE(res);
  11284. EXPECT_EQ(Error::Write, res.error());
  11285. EXPECT_FALSE(smuggled);
  11286. }
  11287. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11288. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11289. // The compressed path builds the whole body before connecting, so this
  11290. // fails client-side and never reaches a server.
  11291. Client cli(HOST, PORT);
  11292. cli.set_compress(true);
  11293. auto res = cli.Post(
  11294. "/", 1024,
  11295. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11296. sink.write("hello", 5);
  11297. sink.done(); // short of the 1024 bytes the request announced
  11298. return true;
  11299. },
  11300. "text/plain");
  11301. ASSERT_FALSE(res);
  11302. EXPECT_EQ(Error::Write, res.error());
  11303. }
  11304. #endif
  11305. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11306. Server svr;
  11307. svr.set_error_handler([](Request const &, Response &res) -> void {
  11308. res.set_chunked_content_provider(
  11309. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11310. sink.os << "hello";
  11311. sink.os << "world";
  11312. sink.done();
  11313. return true;
  11314. });
  11315. });
  11316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11317. auto se = detail::scope_exit([&] {
  11318. svr.stop();
  11319. listen_thread.join();
  11320. ASSERT_FALSE(svr.is_running());
  11321. });
  11322. svr.wait_until_ready();
  11323. Client cli("localhost", PORT);
  11324. auto res = cli.Get("/");
  11325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11327. EXPECT_EQ("helloworld", res->body);
  11328. }
  11329. // A body set after a content provider must replace it, not be sent through it.
  11330. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11331. Server svr;
  11332. svr.set_mount_point("/", "./www");
  11333. svr.set_file_request_handler([](const Request &req, Response &res) {
  11334. if (req.path == "/dir/test.html") {
  11335. res.status = StatusCode::Forbidden_403;
  11336. res.set_content(std::string(5000, 'D'), "text/plain");
  11337. } else if (req.path == "/file") {
  11338. res.status = StatusCode::Forbidden_403;
  11339. res.body = "Denied";
  11340. }
  11341. });
  11342. auto port = svr.bind_to_any_port(HOST);
  11343. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11344. auto se = detail::scope_exit([&] {
  11345. svr.stop();
  11346. t.join();
  11347. ASSERT_FALSE(svr.is_running());
  11348. });
  11349. svr.wait_until_ready();
  11350. Client cli(HOST, port);
  11351. {
  11352. auto res = cli.Get("/dir/test.html");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11355. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11356. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11357. }
  11358. {
  11359. auto res = cli.Get("/file");
  11360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11361. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11362. EXPECT_EQ("Denied", res->body);
  11363. }
  11364. {
  11365. auto res = cli.Get("/dir/index.html");
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. EXPECT_EQ(0U, res->body.find("<html>"));
  11369. }
  11370. }
  11371. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11372. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11373. Server svr;
  11374. std::vector<bool> released;
  11375. std::mutex released_mutex;
  11376. auto releaser = [&](bool success) {
  11377. std::lock_guard<std::mutex> guard(released_mutex);
  11378. released.push_back(success);
  11379. };
  11380. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11381. return sink.write(&"hello"[offset], length);
  11382. };
  11383. svr.Get("/sized", [&](const Request &, Response &res) {
  11384. res.status = StatusCode::NotFound_404;
  11385. res.set_content_provider(5, "text/plain", provider, releaser);
  11386. });
  11387. svr.Get("/chunked", [&](const Request &, Response &res) {
  11388. res.status = StatusCode::ServiceUnavailable_503;
  11389. res.set_chunked_content_provider(
  11390. "text/plain",
  11391. [](size_t, DataSink &sink) {
  11392. sink.os << "chunk";
  11393. sink.done();
  11394. return true;
  11395. },
  11396. releaser);
  11397. });
  11398. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11399. res.set_content_provider(5, "text/plain", provider, releaser);
  11400. throw std::runtime_error("after the provider");
  11401. });
  11402. svr.set_error_handler([](const Request &req, Response &res) {
  11403. // Leave the exception handler's content to it.
  11404. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11405. res.set_content(std::string(1000, 'E'), "text/html");
  11406. return Server::HandlerResponse::Handled;
  11407. });
  11408. svr.set_exception_handler(
  11409. [](const Request &, Response &res, std::exception_ptr) {
  11410. res.status = StatusCode::InternalServerError_500;
  11411. res.set_content(std::string(1000, 'X'), "text/html");
  11412. });
  11413. auto port = svr.bind_to_any_port(HOST);
  11414. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. });
  11420. svr.wait_until_ready();
  11421. Client cli(HOST, port);
  11422. {
  11423. auto res = cli.Get("/sized");
  11424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11426. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11427. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11428. }
  11429. {
  11430. auto res = cli.Get("/chunked");
  11431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11432. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11433. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11434. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11435. }
  11436. {
  11437. auto res = cli.Get("/throw");
  11438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11439. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11440. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11441. }
  11442. std::lock_guard<std::mutex> guard(released_mutex);
  11443. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11444. }
  11445. #endif
  11446. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11447. Server svr;
  11448. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11449. return sink.write(&"abc"[offset], length);
  11450. };
  11451. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11452. res.set_file_content("./www/dir/test.html");
  11453. res.set_content("body", "text/plain");
  11454. });
  11455. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11456. res.set_content(std::string(100, 'B'), "text/plain");
  11457. res.set_file_content("./www/dir/test.html");
  11458. });
  11459. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11460. res.set_content(std::string(100, 'B'), "text/plain");
  11461. res.set_content_provider(3, "text/x-provider", abc);
  11462. });
  11463. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11464. res.set_content_provider(3, "text/x-provider", abc);
  11465. res.set_content(std::string(100, 'B'), "text/plain");
  11466. });
  11467. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11468. res.set_content_provider(3, "text/x-provider", abc);
  11469. res.set_file_content("./www/dir/test.html", "text/x-file");
  11470. });
  11471. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11472. res.set_file_content("./www/dir/test.html");
  11473. res.set_header("Content-Type", "text/x-handler");
  11474. });
  11475. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11476. res.set_content_provider(3, "text/plain", abc);
  11477. res.body = "direct";
  11478. });
  11479. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11480. res.set_file_content("./www/dir/test.html");
  11481. res.body = "direct";
  11482. });
  11483. auto port = svr.bind_to_any_port(HOST);
  11484. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11485. auto se = detail::scope_exit([&] {
  11486. svr.stop();
  11487. t.join();
  11488. ASSERT_FALSE(svr.is_running());
  11489. });
  11490. svr.wait_until_ready();
  11491. Client cli(HOST, port);
  11492. auto expect_body = [&](const char *path, const std::string &body,
  11493. const std::string &type) {
  11494. // Uncompressed, so Content-Length can be compared with the body.
  11495. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11496. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11498. EXPECT_EQ(body, res->body) << path;
  11499. EXPECT_EQ(std::to_string(body.size()),
  11500. res->get_header_value("Content-Length"))
  11501. << path;
  11502. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11503. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11504. };
  11505. expect_body("/file-then-body", "body", "text/plain");
  11506. expect_body("/body-then-file", "test.html", "text/html");
  11507. expect_body("/body-then-provider", "abc", "text/x-provider");
  11508. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11509. expect_body("/provider-then-file", "test.html", "text/x-file");
  11510. expect_body("/file-then-header", "test.html", "text/x-handler");
  11511. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11512. expect_body("/file-then-direct-body", "direct", "text/plain");
  11513. // Ranges are checked against the body, not the dropped provider.
  11514. {
  11515. auto res = cli.Get("/provider-then-direct-body",
  11516. Headers{{make_range_header({{1, 2}})}});
  11517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11519. EXPECT_EQ("ir", res->body);
  11520. }
  11521. {
  11522. auto res = cli.Get("/file-then-direct-body",
  11523. Headers{{make_range_header({{7, 8}})}});
  11524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11525. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11526. }
  11527. }
  11528. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11529. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11530. const char *path = "./truncated_while_served.txt";
  11531. const size_t size = 32 * 1024 * 1024;
  11532. {
  11533. std::ofstream f(path, std::ios::binary);
  11534. f << std::string(size, 'x');
  11535. }
  11536. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11537. // Over TLS, where the bytes are encrypted in this process rather than
  11538. // copied by send().
  11539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11540. svr.Get("/file", [&](const Request &, Response &res) {
  11541. res.set_file_content(path, "text/plain");
  11542. });
  11543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. // The file shrinks once the first bytes are in, as a rewrite in place
  11551. // would, and reading the mapping past its new end used to raise SIGBUS.
  11552. SSLClient cli(HOST, PORT);
  11553. cli.enable_server_certificate_verification(false);
  11554. size_t received = 0;
  11555. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11556. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11557. received += len;
  11558. return true;
  11559. });
  11560. EXPECT_FALSE(res);
  11561. EXPECT_LT(received, size);
  11562. }
  11563. #endif
  11564. // Forward declaration (see the base64_encode note).
  11565. namespace httplib {
  11566. namespace detail {
  11567. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11568. const std::string &content_type,
  11569. EncodingType encoding);
  11570. } // namespace detail
  11571. } // namespace httplib
  11572. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11573. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11574. ASSERT_TRUE(mm->is_open());
  11575. Response res;
  11576. detail::set_file_content_provider(res, mm, "text/html",
  11577. detail::EncodingType::None);
  11578. std::string out;
  11579. DataSink sink;
  11580. sink.write = [&](const char *d, size_t l) {
  11581. out.append(d, l);
  11582. return true;
  11583. };
  11584. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11585. EXPECT_EQ("test.html", out);
  11586. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11587. EXPECT_EQ("test.html", out);
  11588. }
  11589. TEST(LongPollingTest, ClientCloseDetection) {
  11590. Server svr;
  11591. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11592. res.set_chunked_content_provider(
  11593. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11594. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11595. sink.os << "hello";
  11596. auto count = 10;
  11597. while (count > 0 && sink.is_writable()) {
  11598. this_thread::sleep_for(chrono::milliseconds(10));
  11599. count--;
  11600. }
  11601. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11602. return true;
  11603. });
  11604. });
  11605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. listen_thread.join();
  11609. ASSERT_FALSE(svr.is_running());
  11610. });
  11611. svr.wait_until_ready();
  11612. Client cli("localhost", PORT);
  11613. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11614. EXPECT_EQ("hello", string(data, data_length));
  11615. return false; // close the socket immediately.
  11616. });
  11617. ASSERT_FALSE(res);
  11618. }
  11619. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11620. Server svr;
  11621. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11622. res.set_chunked_content_provider(
  11623. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11624. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11625. sink.os << "hello";
  11626. EXPECT_TRUE(sink.os.good());
  11627. // Wait for the client to close the connection
  11628. auto count = 10;
  11629. while (count > 0 && sink.is_writable()) {
  11630. this_thread::sleep_for(chrono::milliseconds(10));
  11631. count--;
  11632. }
  11633. // After client disconnect, write repeatedly until the socket
  11634. // write actually fails (small writes may be absorbed by the
  11635. // kernel buffer)
  11636. std::string chunk(1024, 'x');
  11637. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11638. sink.os << chunk;
  11639. }
  11640. EXPECT_TRUE(sink.os.fail());
  11641. return true;
  11642. });
  11643. });
  11644. auto port = svr.bind_to_any_port("localhost");
  11645. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. listen_thread.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. });
  11651. svr.wait_until_ready();
  11652. Client cli("localhost", port);
  11653. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11654. EXPECT_EQ("hello", string(data, data_length));
  11655. return false; // close the socket immediately.
  11656. });
  11657. ASSERT_FALSE(res);
  11658. }
  11659. TEST(GetWithParametersTest, GetWithParameters) {
  11660. Server svr;
  11661. svr.Get("/", [&](const Request &req, Response &) {
  11662. EXPECT_EQ("world", req.get_param_value("hello"));
  11663. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11664. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11665. });
  11666. svr.Get("/params", [&](const Request &req, Response &) {
  11667. EXPECT_EQ("world", req.get_param_value("hello"));
  11668. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11669. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11670. });
  11671. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11672. EXPECT_EQ("resource-id", req.matches[1]);
  11673. EXPECT_EQ("foo", req.get_param_value("param1"));
  11674. EXPECT_EQ("bar", req.get_param_value("param2"));
  11675. });
  11676. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11677. EXPECT_EQ("user-id", req.path_params.at("id"));
  11678. EXPECT_EQ("foo", req.get_param_value("param1"));
  11679. EXPECT_EQ("bar", req.get_param_value("param2"));
  11680. });
  11681. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. listen_thread.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. {
  11689. Client cli(HOST, PORT);
  11690. Params params;
  11691. params.emplace("hello", "world");
  11692. params.emplace("hello2", "world2");
  11693. params.emplace("hello3", "world3");
  11694. auto res = cli.Get("/", params, Headers{});
  11695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11696. EXPECT_EQ(StatusCode::OK_200, res->status);
  11697. }
  11698. {
  11699. Client cli(HOST, PORT);
  11700. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11702. EXPECT_EQ(StatusCode::OK_200, res->status);
  11703. }
  11704. {
  11705. Client cli(HOST, PORT);
  11706. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. EXPECT_EQ(StatusCode::OK_200, res->status);
  11709. }
  11710. {
  11711. Client cli(HOST, PORT);
  11712. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ(StatusCode::OK_200, res->status);
  11715. }
  11716. }
  11717. TEST(GetWithParametersTest, GetWithParameters2) {
  11718. Server svr;
  11719. svr.Get("/", [&](const Request &req, Response &res) {
  11720. auto text = req.get_param_value("hello");
  11721. res.set_content(text, "text/plain");
  11722. });
  11723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. listen_thread.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. });
  11729. svr.wait_until_ready();
  11730. Client cli("localhost", PORT);
  11731. Params params;
  11732. params.emplace("hello", "world");
  11733. std::string body;
  11734. auto res = cli.Get("/", params, Headers{},
  11735. [&](const char *data, size_t data_length) {
  11736. body.append(data, data_length);
  11737. return true;
  11738. });
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("world", body);
  11742. }
  11743. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11744. Server svr;
  11745. svr.Get("/search", [&](const Request &req, Response &res) {
  11746. auto q = req.get_param_value("q");
  11747. res.set_content(q, "text/plain");
  11748. });
  11749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11750. auto se = detail::scope_exit([&] {
  11751. svr.stop();
  11752. listen_thread.join();
  11753. ASSERT_FALSE(svr.is_running());
  11754. });
  11755. svr.wait_until_ready();
  11756. Client cli("localhost", PORT);
  11757. // Verify that Get(path, params) works without requiring Headers argument
  11758. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::OK_200, res->status);
  11761. EXPECT_EQ("cpp-httplib", res->body);
  11762. }
  11763. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11764. auto host = "httpbingo.org";
  11765. auto path = std::string{"/range/32"};
  11766. #ifdef CPPHTTPLIB_SSL_ENABLED
  11767. SSLClient cli(host);
  11768. #else
  11769. Client cli(host);
  11770. #endif
  11771. cli.set_default_headers({make_range_header({{1, 10}})});
  11772. cli.set_connection_timeout(5);
  11773. {
  11774. auto res = cli.Get(path);
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. EXPECT_EQ("bcdefghijk", res->body);
  11777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11778. }
  11779. {
  11780. auto res = cli.Get(path);
  11781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11782. EXPECT_EQ("bcdefghijk", res->body);
  11783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11784. }
  11785. }
  11786. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11787. Server svr;
  11788. svr.set_default_headers({{"Hello", "World"}});
  11789. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11790. res.set_content("ok", "text/plain");
  11791. });
  11792. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11793. auto se = detail::scope_exit([&] {
  11794. svr.stop();
  11795. listen_thread.join();
  11796. ASSERT_FALSE(svr.is_running());
  11797. });
  11798. svr.wait_until_ready();
  11799. Client cli("localhost", PORT);
  11800. auto res = cli.Get("/");
  11801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11802. EXPECT_EQ(StatusCode::OK_200, res->status);
  11803. EXPECT_EQ("ok", res->body);
  11804. EXPECT_EQ("World", res->get_header_value("Hello"));
  11805. }
  11806. #ifdef CPPHTTPLIB_SSL_ENABLED
  11807. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11809. ASSERT_TRUE(svr.is_valid());
  11810. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11811. std::this_thread::sleep_for(std::chrono::seconds(2));
  11812. res.set_content("a", "text/plain");
  11813. });
  11814. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11815. res.set_content("b", "text/plain");
  11816. });
  11817. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. listen_thread.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. SSLClient cli("localhost", PORT);
  11825. cli.enable_server_certificate_verification(false);
  11826. cli.set_keep_alive(true);
  11827. cli.set_read_timeout(std::chrono::seconds(1));
  11828. auto resa = cli.Get("/a");
  11829. ASSERT_TRUE(!resa);
  11830. EXPECT_EQ(Error::Read, resa.error());
  11831. auto resb = cli.Get("/b");
  11832. ASSERT_TRUE(resb);
  11833. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11834. EXPECT_EQ("b", resb->body);
  11835. }
  11836. // Closing an idle keep-alive connection sends close_notify and returns. The
  11837. // server must not wait for the client's close_notify: an idle client never
  11838. // sends one, so the worker would be held until the read timeout expires, and
  11839. // stop() would wait for it.
  11840. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11842. ASSERT_TRUE(svr.is_valid());
  11843. svr.set_keep_alive_timeout(1);
  11844. svr.set_read_timeout(10, 0);
  11845. svr.Get("/", [](const Request &, Response &res) {
  11846. res.set_content("ok", "text/plain");
  11847. });
  11848. auto port = svr.bind_to_any_port(HOST);
  11849. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11850. auto se = detail::scope_exit([&] {
  11851. if (listen_thread.joinable()) {
  11852. svr.stop();
  11853. listen_thread.join();
  11854. }
  11855. });
  11856. svr.wait_until_ready();
  11857. SSLClient cli(HOST, port);
  11858. cli.enable_server_certificate_verification(false);
  11859. cli.set_keep_alive(true);
  11860. auto res = cli.Get("/");
  11861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11862. EXPECT_EQ(StatusCode::OK_200, res->status);
  11863. // Stay idle past the keep-alive timeout so the server closes the connection.
  11864. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11865. auto start = std::chrono::steady_clock::now();
  11866. svr.stop();
  11867. listen_thread.join();
  11868. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11869. std::chrono::steady_clock::now() - start)
  11870. .count();
  11871. EXPECT_LT(elapsed, 3000);
  11872. }
  11873. #endif
  11874. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11875. protected:
  11876. ServerTestWithAI_PASSIVE()
  11877. : cli_(HOST, PORT)
  11878. #ifdef CPPHTTPLIB_SSL_ENABLED
  11879. ,
  11880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11881. #endif
  11882. {
  11883. #ifdef CPPHTTPLIB_SSL_ENABLED
  11884. cli_.enable_server_certificate_verification(false);
  11885. #endif
  11886. }
  11887. virtual void SetUp() {
  11888. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11889. res.set_content("Hello World!", "text/plain");
  11890. });
  11891. t_ = thread(
  11892. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11893. svr_.wait_until_ready();
  11894. }
  11895. virtual void TearDown() {
  11896. svr_.stop();
  11897. t_.join();
  11898. }
  11899. #ifdef CPPHTTPLIB_SSL_ENABLED
  11900. SSLClient cli_;
  11901. SSLServer svr_;
  11902. #else
  11903. Client cli_;
  11904. Server svr_;
  11905. #endif
  11906. thread t_;
  11907. };
  11908. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11909. auto res = cli_.Get("/hi");
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ(StatusCode::OK_200, res->status);
  11912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11913. EXPECT_EQ("Hello World!", res->body);
  11914. }
  11915. class ServerUpDownTest : public ::testing::Test {
  11916. protected:
  11917. ServerUpDownTest() : cli_(HOST, PORT) {}
  11918. virtual void SetUp() {
  11919. t_ = thread([&]() {
  11920. svr_.bind_to_any_port(HOST);
  11921. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11922. ASSERT_TRUE(svr_.listen_after_bind());
  11923. });
  11924. svr_.wait_until_ready();
  11925. }
  11926. virtual void TearDown() {
  11927. svr_.stop();
  11928. t_.join();
  11929. }
  11930. Client cli_;
  11931. Server svr_;
  11932. thread t_;
  11933. };
  11934. TEST_F(ServerUpDownTest, QuickStartStop) {
  11935. // Should not crash, especially when run with
  11936. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11937. }
  11938. class PayloadMaxLengthTest : public ::testing::Test {
  11939. protected:
  11940. PayloadMaxLengthTest()
  11941. : cli_(HOST, PORT)
  11942. #ifdef CPPHTTPLIB_SSL_ENABLED
  11943. ,
  11944. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11945. #endif
  11946. {
  11947. #ifdef CPPHTTPLIB_SSL_ENABLED
  11948. cli_.enable_server_certificate_verification(false);
  11949. #endif
  11950. }
  11951. virtual void SetUp() {
  11952. svr_.set_payload_max_length(8);
  11953. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11954. res.set_content("test", "text/plain");
  11955. });
  11956. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11957. svr_.wait_until_ready();
  11958. }
  11959. virtual void TearDown() {
  11960. svr_.stop();
  11961. t_.join();
  11962. }
  11963. #ifdef CPPHTTPLIB_SSL_ENABLED
  11964. SSLClient cli_;
  11965. SSLServer svr_;
  11966. #else
  11967. Client cli_;
  11968. Server svr_;
  11969. #endif
  11970. thread t_;
  11971. };
  11972. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11973. auto res = cli_.Post("/test", "123456789", "text/plain");
  11974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11975. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11976. res = cli_.Post("/test", "12345678", "text/plain");
  11977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11978. EXPECT_EQ(StatusCode::OK_200, res->status);
  11979. }
  11980. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11981. // Test chunked encoding with payload exceeding the 8-byte limit
  11982. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11983. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11985. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11986. }
  11987. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11988. // Test chunked encoding with payload within the 8-byte limit
  11989. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11990. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11995. // Test using send_request to send chunked data exceeding payload limit
  11996. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11997. "Host: " +
  11998. std::string(HOST) + ":" + std::to_string(PORT) +
  11999. "\r\n"
  12000. "Transfer-Encoding: chunked\r\n"
  12001. "Connection: close\r\n"
  12002. "\r\n"
  12003. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12004. "0123456789\r\n"
  12005. "0\r\n" // End chunk
  12006. "\r\n";
  12007. std::string response;
  12008. bool result = send_request(1, chunked_request, &response);
  12009. if (!result) {
  12010. // If send_request fails, it might be because the server closed the
  12011. // connection due to payload limit enforcement, which is acceptable
  12012. SUCCEED()
  12013. << "Server rejected oversized chunked request (connection closed)";
  12014. } else {
  12015. // If we got a response, check if it's an error response or connection was
  12016. // closed early Short response length indicates connection was closed due to
  12017. // payload limit
  12018. if (response.length() <= 10) {
  12019. SUCCEED() << "Server closed connection for oversized chunked request";
  12020. } else {
  12021. // Check for error status codes
  12022. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12023. response.find("Payload Too Large") != std::string::npos ||
  12024. response.find("400") != std::string::npos);
  12025. }
  12026. }
  12027. }
  12028. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12029. // Test request without Content-Length header exceeding payload limit
  12030. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12031. "Host: " +
  12032. std::string(HOST) + ":" +
  12033. std::to_string(PORT) +
  12034. "\r\n"
  12035. "Connection: close\r\n"
  12036. "\r\n";
  12037. // Add payload exceeding the 8-byte limit
  12038. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12039. request_without_content_length += large_payload;
  12040. std::string response;
  12041. bool result = send_request(1, request_without_content_length, &response);
  12042. if (!result) {
  12043. // If send_request fails, server likely closed connection due to payload
  12044. // limit
  12045. SUCCEED() << "Server rejected oversized request without Content-Length "
  12046. "(connection closed)";
  12047. } else {
  12048. // Check if server responded with error or closed connection early
  12049. if (response.length() <= 10) {
  12050. SUCCEED() << "Server closed connection for oversized request without "
  12051. "Content-Length";
  12052. } else {
  12053. // Check for error status codes
  12054. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12055. response.find("Payload Too Large") != std::string::npos ||
  12056. response.find("400") != std::string::npos);
  12057. }
  12058. }
  12059. }
  12060. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12061. // Test request without Content-Length header within payload limit
  12062. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12063. "Host: " +
  12064. std::string(HOST) + ":" +
  12065. std::to_string(PORT) +
  12066. "\r\n"
  12067. "Connection: close\r\n"
  12068. "\r\n";
  12069. // Add payload within the 8-byte limit
  12070. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12071. request_without_content_length += small_payload;
  12072. std::string response;
  12073. bool result = send_request(1, request_without_content_length, &response);
  12074. // For requests without Content-Length, the server may have different behavior
  12075. // The key is that it should not reject due to payload limit for small
  12076. // payloads
  12077. if (result) {
  12078. // Check for any HTTP response (success or error, but not connection closed)
  12079. if (response.length() > 10) {
  12080. SUCCEED()
  12081. << "Server processed request without Content-Length within limit";
  12082. } else {
  12083. // Short response might indicate connection closed, which is acceptable
  12084. SUCCEED() << "Server closed connection for request without "
  12085. "Content-Length (acceptable behavior)";
  12086. }
  12087. } else {
  12088. // Connection failure might be due to protocol requirements
  12089. SUCCEED() << "Connection issue with request without Content-Length "
  12090. "(environment-specific)";
  12091. }
  12092. }
  12093. class LargePayloadMaxLengthTest : public ::testing::Test {
  12094. protected:
  12095. LargePayloadMaxLengthTest()
  12096. : cli_(HOST, PORT)
  12097. #ifdef CPPHTTPLIB_SSL_ENABLED
  12098. ,
  12099. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12100. #endif
  12101. {
  12102. #ifdef CPPHTTPLIB_SSL_ENABLED
  12103. cli_.enable_server_certificate_verification(false);
  12104. #endif
  12105. }
  12106. virtual void SetUp() {
  12107. // Set 10MB payload limit
  12108. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12109. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12110. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12111. res.set_content("Large payload test", "text/plain");
  12112. });
  12113. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12114. svr_.wait_until_ready();
  12115. }
  12116. virtual void TearDown() {
  12117. svr_.stop();
  12118. t_.join();
  12119. }
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. SSLClient cli_;
  12122. SSLServer svr_;
  12123. #else
  12124. Client cli_;
  12125. Server svr_;
  12126. #endif
  12127. thread t_;
  12128. };
  12129. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12130. // Test chunked encoding with payload within 10MB limit
  12131. std::string medium_payload(5 * 1024 * 1024,
  12132. 'A'); // 5MB payload, within 10MB limit
  12133. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12135. EXPECT_EQ(StatusCode::OK_200, res->status);
  12136. }
  12137. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12138. // Test chunked encoding with payload exceeding 10MB limit
  12139. std::string large_payload(12 * 1024 * 1024,
  12140. 'B'); // 12MB payload, exceeds 10MB limit
  12141. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12142. // Server may either return 413 or close the connection
  12143. if (res) {
  12144. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12145. } else {
  12146. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12147. }
  12148. }
  12149. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12150. // Test request without Content-Length header within 10MB limit
  12151. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12152. "Host: " +
  12153. std::string(HOST) + ":" +
  12154. std::to_string(PORT) +
  12155. "\r\n"
  12156. "Connection: close\r\n"
  12157. "\r\n";
  12158. // Add 1MB payload (within 10MB limit)
  12159. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12160. request_without_content_length += medium_payload;
  12161. std::string response;
  12162. bool result = send_request(5, request_without_content_length, &response);
  12163. if (result) {
  12164. // Should get a proper HTTP response for payloads within limit
  12165. if (response.length() > 10) {
  12166. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12167. "10MB limit";
  12168. } else {
  12169. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12170. "Content-Length)";
  12171. }
  12172. } else {
  12173. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12174. }
  12175. }
  12176. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12177. // Test request without Content-Length header exceeding 10MB limit
  12178. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12179. "Host: " +
  12180. std::string(HOST) + ":" +
  12181. std::to_string(PORT) +
  12182. "\r\n"
  12183. "Connection: close\r\n"
  12184. "\r\n";
  12185. // Add 12MB payload (exceeds 10MB limit)
  12186. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12187. request_without_content_length += large_payload;
  12188. std::string response;
  12189. bool result = send_request(10, request_without_content_length, &response);
  12190. if (!result) {
  12191. // Server should close connection due to payload limit
  12192. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12193. "(connection closed)";
  12194. } else {
  12195. // Check for error response
  12196. if (response.length() <= 10) {
  12197. SUCCEED()
  12198. << "Server closed connection for 12MB request exceeding 10MB limit";
  12199. } else {
  12200. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12201. response.find("Payload Too Large") != std::string::npos ||
  12202. response.find("400") != std::string::npos);
  12203. }
  12204. }
  12205. }
  12206. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12207. Server svr;
  12208. svr.Get("/", [](const Request &, Response &res) {
  12209. // Claims the most the client accepts, far more than it sends, then drops
  12210. // the connection.
  12211. res.set_content_provider(std::string().max_size(), "text/plain",
  12212. [](size_t, size_t, DataSink &sink) {
  12213. sink.write("abc", 3);
  12214. return false;
  12215. });
  12216. });
  12217. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12218. auto se = detail::scope_exit([&] {
  12219. svr.stop();
  12220. thread.join();
  12221. ASSERT_FALSE(svr.is_running());
  12222. });
  12223. svr.wait_until_ready();
  12224. Client cli(HOST, PORT);
  12225. cli.set_payload_max_length(0);
  12226. EXPECT_FALSE(cli.Get("/"));
  12227. }
  12228. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12229. // Stream API does, not as a plain read failure
  12230. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12231. Server svr;
  12232. svr.Get("/big", [](const Request &, Response &res) {
  12233. res.set_content(std::string(100000, 'b'), "text/plain");
  12234. });
  12235. auto port = svr.bind_to_any_port(HOST);
  12236. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. thread.join();
  12240. });
  12241. svr.wait_until_ready();
  12242. Client cli(HOST, port);
  12243. cli.set_payload_max_length(1000);
  12244. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12245. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12246. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12247. [](const char *, size_t) { return true; });
  12248. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12249. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12250. // Small on the wire, over the limit once decompressed
  12251. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12252. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12253. #endif
  12254. }
  12255. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12256. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12257. // path.
  12258. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12259. Server svr;
  12260. const size_t LIMIT = 64 * 1024; // 64KB
  12261. svr.set_payload_max_length(LIMIT);
  12262. size_t total = 0;
  12263. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12264. const ContentReader &content_reader) {
  12265. content_reader([&](const char * /*data*/, size_t len) {
  12266. total += len;
  12267. return true;
  12268. });
  12269. res.status = 200;
  12270. res.set_content("stream_ok", "text/plain");
  12271. });
  12272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12273. auto se = detail::scope_exit([&] {
  12274. svr.stop();
  12275. thread.join();
  12276. ASSERT_FALSE(svr.is_running());
  12277. });
  12278. svr.wait_until_ready();
  12279. // Prepare 256KB raw data and gzip-compress it
  12280. std::string raw(256 * 1024, 'A');
  12281. std::string gz;
  12282. {
  12283. z_stream zs{};
  12284. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12285. Z_DEFAULT_STRATEGY);
  12286. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12287. zs.avail_in = static_cast<uInt>(raw.size());
  12288. char outbuf[4096];
  12289. int ret;
  12290. do {
  12291. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12292. zs.avail_out = sizeof(outbuf);
  12293. ret = deflate(&zs, Z_FINISH);
  12294. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12295. } while (ret != Z_STREAM_END);
  12296. deflateEnd(&zs);
  12297. }
  12298. Client cli(HOST, PORT);
  12299. cli.set_connection_timeout(std::chrono::seconds(5));
  12300. Headers headers = {{"Content-Encoding", "gzip"}};
  12301. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12302. "application/octet-stream");
  12303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12304. // Server must reject oversized decompressed payloads with 413.
  12305. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12306. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12307. EXPECT_LE(total, LIMIT);
  12308. }
  12309. #ifndef CPPHTTPLIB_SSL_ENABLED
  12310. // For a request with neither Content-Length nor Transfer-Encoding, the
  12311. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12312. // compressed wire bytes straight to the ContentReader without ever routing
  12313. // them through the decompressor, so payload_max_length_ only bounded the
  12314. // compressed size on the wire, not the decompressed size.
  12315. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12316. Server svr;
  12317. const size_t LIMIT = 64 * 1024; // 64KB
  12318. svr.set_payload_max_length(LIMIT);
  12319. size_t total = 0;
  12320. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12321. const ContentReader &content_reader) {
  12322. content_reader([&](const char * /*data*/, size_t len) {
  12323. total += len;
  12324. return true;
  12325. });
  12326. res.status = 200;
  12327. res.set_content("stream_ok", "text/plain");
  12328. });
  12329. auto port = svr.bind_to_any_port(HOST);
  12330. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12331. auto se = detail::scope_exit([&] {
  12332. svr.stop();
  12333. thread.join();
  12334. ASSERT_FALSE(svr.is_running());
  12335. });
  12336. svr.wait_until_ready();
  12337. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12338. // StreamingGzipDecompression test above.
  12339. std::string raw(256 * 1024, 'A');
  12340. std::string gz;
  12341. {
  12342. httplib::detail::gzip_compressor compressor;
  12343. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12344. [&](const char *chunk, size_t len) {
  12345. gz.append(chunk, len);
  12346. return true;
  12347. });
  12348. ASSERT_TRUE(result);
  12349. }
  12350. // Send the gzip body over raw TCP with neither Content-Length nor
  12351. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12352. // kicks in.
  12353. std::string req = "POST /stream HTTP/1.1\r\n"
  12354. "Host: " +
  12355. std::string(HOST) + ":" + std::to_string(port) +
  12356. "\r\n"
  12357. "Content-Encoding: gzip\r\n"
  12358. "Connection: close\r\n"
  12359. "\r\n" +
  12360. gz;
  12361. std::string response;
  12362. ASSERT_TRUE(send_request(5, req, &response, port));
  12363. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12364. EXPECT_LE(total, LIMIT);
  12365. }
  12366. #endif
  12367. #endif
  12368. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12369. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12370. // the payload must be passed through untouched instead of being rejected.
  12371. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12372. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12373. Server svr;
  12374. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12375. res.set_content(body, "image/jpeg");
  12376. res.set_header("Content-Encoding", "UTF-8");
  12377. });
  12378. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12379. res.set_content(body, "image/jpeg");
  12380. res.set_header("Content-Encoding", "identity");
  12381. });
  12382. svr.Post("/echo", [](const Request &req, Response &res) {
  12383. res.set_content(req.body, "image/jpeg");
  12384. });
  12385. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. t.join();
  12389. ASSERT_FALSE(svr.is_running());
  12390. });
  12391. svr.wait_until_ready();
  12392. Client cli(HOST, PORT);
  12393. {
  12394. auto res = cli.Get("/image");
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::OK_200, res->status);
  12397. EXPECT_EQ(body, res->body);
  12398. }
  12399. {
  12400. auto res = cli.Get("/identity");
  12401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12402. EXPECT_EQ(StatusCode::OK_200, res->status);
  12403. EXPECT_EQ(body, res->body);
  12404. }
  12405. {
  12406. // The same applies to a request body reaching the server.
  12407. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12408. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12410. EXPECT_EQ(StatusCode::OK_200, res->status);
  12411. EXPECT_EQ(body, res->body);
  12412. }
  12413. }
  12414. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12415. // gzip-encoded response even when the build has no zlib support.
  12416. static const char GZIPPED_HELLO_WORLD[] = {
  12417. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12418. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12419. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12420. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12421. // A content coding is a whole token, not something the field value merely
  12422. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12423. // as "fibre" look like Brotli, and turned a multi-coding value like
  12424. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12425. // it was never meant to see.
  12426. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12427. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12428. Server svr;
  12429. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12430. res.set_content(body, "image/jpeg");
  12431. res.set_header("Content-Encoding", "fibre");
  12432. });
  12433. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12434. res.set_content(body, "image/jpeg");
  12435. res.set_header("Content-Encoding", "gzip, br");
  12436. });
  12437. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12438. res.set_content(body, "image/jpeg");
  12439. res.set_header("Content-Encoding", "x-zstd-ish");
  12440. });
  12441. auto port = svr.bind_to_any_port(HOST);
  12442. thread t = thread([&]() { svr.listen_after_bind(); });
  12443. auto se = detail::scope_exit([&] {
  12444. svr.stop();
  12445. t.join();
  12446. ASSERT_FALSE(svr.is_running());
  12447. });
  12448. svr.wait_until_ready();
  12449. Client cli(HOST, port);
  12450. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12451. auto res = cli.Get(path);
  12452. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12453. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12454. // Not a coding we recognize, so the payload comes back untouched
  12455. EXPECT_EQ(body, res->body) << path;
  12456. }
  12457. }
  12458. // A content coding cpp-httplib recognizes but was not built with must be
  12459. // reported as such. Handing the still-compressed payload back to the caller
  12460. // would silently corrupt it.
  12461. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12462. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12463. Server svr;
  12464. // "image/jpeg" keeps the server from applying a content coding of its own,
  12465. // so the hand-crafted Content-Encoding below survives.
  12466. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12467. res.set_content(gzipped, "image/jpeg");
  12468. res.set_header("Content-Encoding", "gzip");
  12469. });
  12470. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12471. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12472. res.set_content(gzipped, "image/jpeg");
  12473. res.set_header("Content-Encoding", "GZIP");
  12474. });
  12475. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12476. auto se = detail::scope_exit([&] {
  12477. svr.stop();
  12478. t.join();
  12479. ASSERT_FALSE(svr.is_running());
  12480. });
  12481. svr.wait_until_ready();
  12482. Client cli(HOST, PORT);
  12483. {
  12484. auto res = cli.Get("/gzipped");
  12485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ("Hello World!", res->body);
  12488. #else
  12489. ASSERT_FALSE(res);
  12490. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12491. #endif
  12492. }
  12493. {
  12494. // open_stream() must behave the same way.
  12495. auto handle = cli.open_stream("GET", "/gzipped");
  12496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12497. ASSERT_TRUE(handle.is_valid());
  12498. std::string received;
  12499. char buf[256];
  12500. ssize_t n;
  12501. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12502. received.append(buf, static_cast<size_t>(n));
  12503. }
  12504. EXPECT_EQ("Hello World!", received);
  12505. #else
  12506. EXPECT_FALSE(handle.is_valid());
  12507. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12508. #endif
  12509. }
  12510. {
  12511. // A differently-cased coding must not be mistaken for an unknown one, or
  12512. // the body would be handed back still compressed.
  12513. auto res = cli.Get("/gzipped-uppercase");
  12514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. EXPECT_EQ("Hello World!", res->body);
  12517. #else
  12518. ASSERT_FALSE(res);
  12519. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12520. #endif
  12521. }
  12522. }
  12523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12524. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12525. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12526. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12527. // body a second time and appending a second Content-Encoding field line, so
  12528. // clients that decode one coding per listed value handed back raw gzip bytes.
  12529. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12530. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12531. Server svr;
  12532. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12533. // keeps the server from applying a coding of its own.
  12534. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12535. res.set_content(gzipped, "text/plain");
  12536. res.set_header("Content-Encoding", "gzip");
  12537. });
  12538. auto port = svr.bind_to_any_port(HOST);
  12539. thread t = thread([&]() { svr.listen_after_bind(); });
  12540. auto se = detail::scope_exit([&] {
  12541. svr.stop();
  12542. t.join();
  12543. ASSERT_FALSE(svr.is_running());
  12544. });
  12545. svr.wait_until_ready();
  12546. Client cli(HOST, port);
  12547. Headers headers = {{"Accept-Encoding", "gzip"}};
  12548. auto res = cli.Get("/pre-gzipped", headers);
  12549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12550. EXPECT_EQ(StatusCode::OK_200, res->status);
  12551. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12552. EXPECT_EQ("Hello World!", res->body);
  12553. }
  12554. // A chunked provider settles its coding where the headers are written and
  12555. // reuses it at write time. Both ends of that have to hold: a handler's own
  12556. // Content-Encoding suppresses the coding, and a response without one is still
  12557. // compressed as it always was.
  12558. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12559. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12560. const std::string plain = "Hello World! Hello World! Hello World!";
  12561. Server svr;
  12562. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12563. res.set_header("Content-Encoding", "gzip");
  12564. res.set_chunked_content_provider(
  12565. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12566. sink.write(gzipped.data(), gzipped.size());
  12567. sink.done();
  12568. return true;
  12569. });
  12570. });
  12571. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12572. res.set_chunked_content_provider(
  12573. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12574. sink.write(plain.data(), plain.size());
  12575. sink.done();
  12576. return true;
  12577. });
  12578. });
  12579. auto port = svr.bind_to_any_port(HOST);
  12580. thread t = thread([&]() { svr.listen_after_bind(); });
  12581. auto se = detail::scope_exit([&] {
  12582. svr.stop();
  12583. t.join();
  12584. ASSERT_FALSE(svr.is_running());
  12585. });
  12586. svr.wait_until_ready();
  12587. Client cli(HOST, port);
  12588. Headers headers = {{"Accept-Encoding", "gzip"}};
  12589. {
  12590. auto res = cli.Get("/pre-gzipped", headers);
  12591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12592. EXPECT_EQ(StatusCode::OK_200, res->status);
  12593. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12594. EXPECT_EQ("Hello World!", res->body);
  12595. }
  12596. {
  12597. auto res = cli.Get("/negotiated", headers);
  12598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12599. EXPECT_EQ(StatusCode::OK_200, res->status);
  12600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12601. EXPECT_EQ(plain, res->body);
  12602. }
  12603. }
  12604. #endif
  12605. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12606. // the same message as the comma-joined one, so both have to be read the same
  12607. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12608. // single gzip coding, and a body the sender says was encoded twice was handed
  12609. // back after one pass, still compressed but presented as decoded.
  12610. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12611. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12612. Server svr;
  12613. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12614. res.set_content(body, "image/jpeg");
  12615. res.headers.emplace("Content-Encoding", "gzip");
  12616. res.headers.emplace("Content-Encoding", "gzip");
  12617. });
  12618. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12619. res.set_content(body, "image/jpeg");
  12620. res.set_header("Content-Encoding", "gzip, gzip");
  12621. });
  12622. auto port = svr.bind_to_any_port(HOST);
  12623. thread t = thread([&]() { svr.listen_after_bind(); });
  12624. auto se = detail::scope_exit([&] {
  12625. svr.stop();
  12626. t.join();
  12627. ASSERT_FALSE(svr.is_running());
  12628. });
  12629. svr.wait_until_ready();
  12630. Client cli(HOST, port);
  12631. // Two codings is not something cpp-httplib decodes, so both representations
  12632. // take the pass-through path rather than one of them being gunzipped once.
  12633. for (const char *path : {"/split", "/joined"}) {
  12634. auto res = cli.Get(path);
  12635. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12636. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12637. EXPECT_EQ(body, res->body) << path;
  12638. }
  12639. }
  12640. // Regression test for DoS vulnerability: a malicious server sending a response
  12641. // without Content-Length header must not cause unbounded memory consumption on
  12642. // the client side. The client should stop reading after a reasonable limit,
  12643. // similar to the server-side set_payload_max_length protection.
  12644. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12645. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12646. #ifndef _WIN32
  12647. signal(SIGPIPE, SIG_IGN);
  12648. #endif
  12649. auto server_thread = std::thread([] {
  12650. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12651. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12652. default_socket_options(srv);
  12653. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12654. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12655. sockaddr_in addr{};
  12656. addr.sin_family = AF_INET;
  12657. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12658. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12659. int opt = 1;
  12660. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12661. #ifdef _WIN32
  12662. reinterpret_cast<const char *>(&opt),
  12663. #else
  12664. &opt,
  12665. #endif
  12666. sizeof(opt));
  12667. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12668. ::listen(srv, 1);
  12669. sockaddr_in cli_addr{};
  12670. socklen_t cli_len = sizeof(cli_addr);
  12671. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12672. if (cli != INVALID_SOCKET) {
  12673. char buf[4096];
  12674. ::recv(cli, buf, sizeof(buf), 0);
  12675. // Malicious response: no Content-Length, no chunked encoding
  12676. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12677. "Connection: close\r\n"
  12678. "\r\n";
  12679. ::send(cli,
  12680. #ifdef _WIN32
  12681. static_cast<const char *>(response_header.c_str()),
  12682. static_cast<int>(response_header.size()),
  12683. #else
  12684. response_header.c_str(), response_header.size(),
  12685. #endif
  12686. 0);
  12687. // Send 10MB of data
  12688. std::string chunk(64 * 1024, 'A');
  12689. size_t total_sent = 0;
  12690. while (total_sent < MALICIOUS_DATA_SIZE) {
  12691. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12692. auto sent = ::send(cli,
  12693. #ifdef _WIN32
  12694. static_cast<const char *>(chunk.c_str()),
  12695. static_cast<int>(to_send),
  12696. #else
  12697. chunk.c_str(), to_send,
  12698. #endif
  12699. 0);
  12700. if (sent <= 0) break;
  12701. total_sent += static_cast<size_t>(sent);
  12702. }
  12703. detail::close_socket(cli);
  12704. }
  12705. detail::close_socket(srv);
  12706. });
  12707. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12708. size_t total_read = 0;
  12709. {
  12710. Client cli("127.0.0.1", PORT + 2);
  12711. cli.set_read_timeout(5, 0);
  12712. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12713. auto stream = cli.open_stream("GET", "/malicious");
  12714. ASSERT_TRUE(stream.is_valid());
  12715. char buffer[64 * 1024];
  12716. ssize_t n;
  12717. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12718. total_read += static_cast<size_t>(n);
  12719. }
  12720. } // StreamHandle and Client destroyed here, closing the socket
  12721. server_thread.join();
  12722. // With set_payload_max_length, the client must stop reading before consuming
  12723. // all 10MB. The read loop should be cut off at or near the configured limit.
  12724. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12725. << "Client read " << total_read << " bytes, exceeding the configured "
  12726. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12727. }
  12728. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12729. // the entire response body without truncation.
  12730. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12731. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12732. #ifndef _WIN32
  12733. signal(SIGPIPE, SIG_IGN);
  12734. #endif
  12735. auto server_thread = std::thread([] {
  12736. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12737. default_socket_options(srv);
  12738. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12740. sockaddr_in addr{};
  12741. addr.sin_family = AF_INET;
  12742. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12743. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12744. int opt = 1;
  12745. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12746. #ifdef _WIN32
  12747. reinterpret_cast<const char *>(&opt),
  12748. #else
  12749. &opt,
  12750. #endif
  12751. sizeof(opt));
  12752. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12753. ::listen(srv, 1);
  12754. sockaddr_in cli_addr{};
  12755. socklen_t cli_len = sizeof(cli_addr);
  12756. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12757. if (cli != INVALID_SOCKET) {
  12758. char buf[4096];
  12759. ::recv(cli, buf, sizeof(buf), 0);
  12760. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12761. "Connection: close\r\n"
  12762. "\r\n";
  12763. ::send(cli,
  12764. #ifdef _WIN32
  12765. static_cast<const char *>(response_header.c_str()),
  12766. static_cast<int>(response_header.size()),
  12767. #else
  12768. response_header.c_str(), response_header.size(),
  12769. #endif
  12770. 0);
  12771. std::string chunk(64 * 1024, 'A');
  12772. size_t total_sent = 0;
  12773. while (total_sent < DATA_SIZE) {
  12774. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12775. auto sent = ::send(cli,
  12776. #ifdef _WIN32
  12777. static_cast<const char *>(chunk.c_str()),
  12778. static_cast<int>(to_send),
  12779. #else
  12780. chunk.c_str(), to_send,
  12781. #endif
  12782. 0);
  12783. if (sent <= 0) break;
  12784. total_sent += static_cast<size_t>(sent);
  12785. }
  12786. #ifdef _WIN32
  12787. ::shutdown(cli, SD_SEND);
  12788. #else
  12789. ::shutdown(cli, SHUT_WR);
  12790. #endif
  12791. // Drain until the client closes its end, ensuring all data is delivered
  12792. char drain[1024];
  12793. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12794. detail::close_socket(cli);
  12795. }
  12796. detail::close_socket(srv);
  12797. });
  12798. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12799. size_t total_read = 0;
  12800. {
  12801. Client cli("127.0.0.1", PORT + 2);
  12802. cli.set_read_timeout(5, 0);
  12803. cli.set_payload_max_length(0); // 0 means no limit
  12804. auto stream = cli.open_stream("GET", "/data");
  12805. ASSERT_TRUE(stream.is_valid());
  12806. char buffer[64 * 1024];
  12807. ssize_t n;
  12808. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12809. total_read += static_cast<size_t>(n);
  12810. }
  12811. }
  12812. server_thread.join();
  12813. EXPECT_EQ(total_read, DATA_SIZE)
  12814. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12815. << " bytes without truncation, but only read " << total_read << " bytes.";
  12816. }
  12817. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12818. // enormous Content-Length must not cause the client to pre-allocate a huge
  12819. // response body buffer. The reservation is capped at payload_max_length_, and
  12820. // the read itself fails when the body exceeds the limit.
  12821. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12822. #ifndef _WIN32
  12823. signal(SIGPIPE, SIG_IGN);
  12824. #endif
  12825. auto server_thread = std::thread([] {
  12826. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12827. default_socket_options(srv);
  12828. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12830. sockaddr_in addr{};
  12831. addr.sin_family = AF_INET;
  12832. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12833. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12834. int opt = 1;
  12835. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12836. #ifdef _WIN32
  12837. reinterpret_cast<const char *>(&opt),
  12838. #else
  12839. &opt,
  12840. #endif
  12841. sizeof(opt));
  12842. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12843. ::listen(srv, 1);
  12844. sockaddr_in cli_addr{};
  12845. socklen_t cli_len = sizeof(cli_addr);
  12846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12847. if (cli != INVALID_SOCKET) {
  12848. char buf[4096];
  12849. ::recv(cli, buf, sizeof(buf), 0);
  12850. // Malicious response: claim a 20GB body but send only a tiny payload.
  12851. std::string response = "HTTP/1.1 200 OK\r\n"
  12852. "Content-Length: 20000000000\r\n"
  12853. "\r\n"
  12854. "abc";
  12855. ::send(cli,
  12856. #ifdef _WIN32
  12857. static_cast<const char *>(response.c_str()),
  12858. static_cast<int>(response.size()),
  12859. #else
  12860. response.c_str(), response.size(),
  12861. #endif
  12862. 0);
  12863. detail::close_socket(cli);
  12864. }
  12865. detail::close_socket(srv);
  12866. });
  12867. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12868. {
  12869. Client cli("127.0.0.1", PORT + 2);
  12870. cli.set_read_timeout(5, 0);
  12871. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12872. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12873. // (server claims more bytes than payload_max_length permits), but it must
  12874. // not exhaust memory before getting there.
  12875. auto res = cli.Get("/malicious");
  12876. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12877. }
  12878. server_thread.join();
  12879. }
  12880. // Verify that content_receiver bypasses the default payload_max_length,
  12881. // allowing streaming downloads larger than 100MB without requiring an explicit
  12882. // set_payload_max_length call.
  12883. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12884. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12885. #ifndef _WIN32
  12886. signal(SIGPIPE, SIG_IGN);
  12887. #endif
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12893. sockaddr_in addr{};
  12894. addr.sin_family = AF_INET;
  12895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12897. int opt = 1;
  12898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12899. #ifdef _WIN32
  12900. reinterpret_cast<const char *>(&opt),
  12901. #else
  12902. &opt,
  12903. #endif
  12904. sizeof(opt));
  12905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12906. ::listen(srv, 1);
  12907. sockaddr_in cli_addr{};
  12908. socklen_t cli_len = sizeof(cli_addr);
  12909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12910. if (cli != INVALID_SOCKET) {
  12911. char buf[4096];
  12912. ::recv(cli, buf, sizeof(buf), 0);
  12913. // Response with Content-Length larger than default 100MB limit
  12914. auto content_length = std::to_string(DATA_SIZE);
  12915. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12916. "Content-Length: " +
  12917. content_length +
  12918. "\r\n"
  12919. "Connection: close\r\n"
  12920. "\r\n";
  12921. ::send(cli,
  12922. #ifdef _WIN32
  12923. static_cast<const char *>(response_header.c_str()),
  12924. static_cast<int>(response_header.size()),
  12925. #else
  12926. response_header.c_str(), response_header.size(),
  12927. #endif
  12928. 0);
  12929. std::string chunk(64 * 1024, 'A');
  12930. size_t total_sent = 0;
  12931. while (total_sent < DATA_SIZE) {
  12932. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12933. auto sent = ::send(cli,
  12934. #ifdef _WIN32
  12935. static_cast<const char *>(chunk.c_str()),
  12936. static_cast<int>(to_send),
  12937. #else
  12938. chunk.c_str(), to_send,
  12939. #endif
  12940. 0);
  12941. if (sent <= 0) break;
  12942. total_sent += static_cast<size_t>(sent);
  12943. }
  12944. detail::close_socket(cli);
  12945. }
  12946. detail::close_socket(srv);
  12947. });
  12948. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12949. size_t total_received = 0;
  12950. {
  12951. Client cli("127.0.0.1", PORT + 2);
  12952. cli.set_read_timeout(10, 0);
  12953. // Do NOT call set_payload_max_length — use the default 100MB limit
  12954. auto res =
  12955. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12956. total_received += data_length;
  12957. return true;
  12958. });
  12959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12960. EXPECT_EQ(StatusCode::OK_200, res->status);
  12961. }
  12962. server_thread.join();
  12963. EXPECT_EQ(total_received, DATA_SIZE)
  12964. << "With content_receiver, the client should read all " << DATA_SIZE
  12965. << " bytes despite the default 100MB payload_max_length, but only read "
  12966. << total_received << " bytes.";
  12967. }
  12968. // Verify that an explicit set_payload_max_length smaller than the response is
  12969. // enforced even when a content_receiver is used.
  12970. TEST(ClientVulnerabilityTest,
  12971. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12972. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12973. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12974. #ifndef _WIN32
  12975. signal(SIGPIPE, SIG_IGN);
  12976. #endif
  12977. auto server_thread = std::thread([] {
  12978. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12979. default_socket_options(srv);
  12980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12981. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12982. sockaddr_in addr{};
  12983. addr.sin_family = AF_INET;
  12984. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12985. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12986. int opt = 1;
  12987. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12988. #ifdef _WIN32
  12989. reinterpret_cast<const char *>(&opt),
  12990. #else
  12991. &opt,
  12992. #endif
  12993. sizeof(opt));
  12994. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12995. ::listen(srv, 1);
  12996. sockaddr_in cli_addr{};
  12997. socklen_t cli_len = sizeof(cli_addr);
  12998. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12999. if (cli != INVALID_SOCKET) {
  13000. char buf[4096];
  13001. ::recv(cli, buf, sizeof(buf), 0);
  13002. auto content_length = std::to_string(DATA_SIZE);
  13003. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13004. "Content-Length: " +
  13005. content_length +
  13006. "\r\n"
  13007. "Connection: close\r\n"
  13008. "\r\n";
  13009. ::send(cli,
  13010. #ifdef _WIN32
  13011. static_cast<const char *>(response_header.c_str()),
  13012. static_cast<int>(response_header.size()),
  13013. #else
  13014. response_header.c_str(), response_header.size(),
  13015. #endif
  13016. 0);
  13017. std::string chunk(64 * 1024, 'A');
  13018. size_t total_sent = 0;
  13019. while (total_sent < DATA_SIZE) {
  13020. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13021. auto sent = ::send(cli,
  13022. #ifdef _WIN32
  13023. static_cast<const char *>(chunk.c_str()),
  13024. static_cast<int>(to_send),
  13025. #else
  13026. chunk.c_str(), to_send,
  13027. #endif
  13028. 0);
  13029. if (sent <= 0) break;
  13030. total_sent += static_cast<size_t>(sent);
  13031. }
  13032. detail::close_socket(cli);
  13033. }
  13034. detail::close_socket(srv);
  13035. });
  13036. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13037. size_t total_received = 0;
  13038. {
  13039. Client cli("127.0.0.1", PORT + 2);
  13040. cli.set_read_timeout(10, 0);
  13041. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13042. auto res =
  13043. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13044. total_received += data_length;
  13045. return true;
  13046. });
  13047. // Should fail because 200MB exceeds the explicit 150MB limit
  13048. EXPECT_FALSE(res);
  13049. }
  13050. server_thread.join();
  13051. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13052. << "Client with content_receiver should respect the explicit "
  13053. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13054. << total_received << " bytes.";
  13055. }
  13056. // Verify that an explicit set_payload_max_length larger than the response
  13057. // allows the content_receiver to read all data successfully.
  13058. TEST(ClientVulnerabilityTest,
  13059. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13060. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13061. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13062. #ifndef _WIN32
  13063. signal(SIGPIPE, SIG_IGN);
  13064. #endif
  13065. auto server_thread = std::thread([] {
  13066. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13067. default_socket_options(srv);
  13068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13069. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13070. sockaddr_in addr{};
  13071. addr.sin_family = AF_INET;
  13072. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13074. int opt = 1;
  13075. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13076. #ifdef _WIN32
  13077. reinterpret_cast<const char *>(&opt),
  13078. #else
  13079. &opt,
  13080. #endif
  13081. sizeof(opt));
  13082. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13083. ::listen(srv, 1);
  13084. sockaddr_in cli_addr{};
  13085. socklen_t cli_len = sizeof(cli_addr);
  13086. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13087. if (cli != INVALID_SOCKET) {
  13088. char buf[4096];
  13089. ::recv(cli, buf, sizeof(buf), 0);
  13090. auto content_length = std::to_string(DATA_SIZE);
  13091. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13092. "Content-Length: " +
  13093. content_length +
  13094. "\r\n"
  13095. "Connection: close\r\n"
  13096. "\r\n";
  13097. ::send(cli,
  13098. #ifdef _WIN32
  13099. static_cast<const char *>(response_header.c_str()),
  13100. static_cast<int>(response_header.size()),
  13101. #else
  13102. response_header.c_str(), response_header.size(),
  13103. #endif
  13104. 0);
  13105. std::string chunk(64 * 1024, 'A');
  13106. size_t total_sent = 0;
  13107. while (total_sent < DATA_SIZE) {
  13108. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13109. auto sent = ::send(cli,
  13110. #ifdef _WIN32
  13111. static_cast<const char *>(chunk.c_str()),
  13112. static_cast<int>(to_send),
  13113. #else
  13114. chunk.c_str(), to_send,
  13115. #endif
  13116. 0);
  13117. if (sent <= 0) break;
  13118. total_sent += static_cast<size_t>(sent);
  13119. }
  13120. #ifdef _WIN32
  13121. ::shutdown(cli, SD_SEND);
  13122. #else
  13123. ::shutdown(cli, SHUT_WR);
  13124. #endif
  13125. char drain[1024];
  13126. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13127. detail::close_socket(cli);
  13128. }
  13129. detail::close_socket(srv);
  13130. });
  13131. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13132. size_t total_received = 0;
  13133. {
  13134. Client cli("127.0.0.1", PORT + 2);
  13135. cli.set_read_timeout(10, 0);
  13136. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13137. auto res =
  13138. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13139. total_received += data_length;
  13140. return true;
  13141. });
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. EXPECT_EQ(StatusCode::OK_200, res->status);
  13144. }
  13145. server_thread.join();
  13146. EXPECT_EQ(total_received, DATA_SIZE)
  13147. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13148. << " bytes (larger than " << DATA_SIZE
  13149. << " bytes response), content_receiver should read all data, but only "
  13150. "read "
  13151. << total_received << " bytes.";
  13152. }
  13153. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13154. // Regression test for "zip bomb" attack on the client side: a malicious server
  13155. // sends a small gzip-compressed response that decompresses to a huge payload.
  13156. // The client must enforce payload_max_length on the decompressed size.
  13157. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13158. constexpr size_t DECOMPRESSED_SIZE =
  13159. 10 * 1024 * 1024; // 10MB after decompression
  13160. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13161. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13162. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13163. std::string compressed;
  13164. {
  13165. httplib::detail::gzip_compressor compressor;
  13166. bool ok =
  13167. compressor.compress(uncompressed.data(), uncompressed.size(),
  13168. /*last=*/true, [&](const char *buf, size_t len) {
  13169. compressed.append(buf, len);
  13170. return true;
  13171. });
  13172. ASSERT_TRUE(ok);
  13173. }
  13174. // Sanity: compressed data should be much smaller than the decompressed size
  13175. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13176. #ifndef _WIN32
  13177. signal(SIGPIPE, SIG_IGN);
  13178. #endif
  13179. // Set up the listening socket in the main thread so the server is guaranteed
  13180. // to be ready before the client connects (eliminates race condition).
  13181. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13182. default_socket_options(srv);
  13183. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13184. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13185. sockaddr_in addr{};
  13186. addr.sin_family = AF_INET;
  13187. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13188. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13189. int opt = 1;
  13190. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13191. #ifdef _WIN32
  13192. reinterpret_cast<const char *>(&opt),
  13193. #else
  13194. &opt,
  13195. #endif
  13196. sizeof(opt));
  13197. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13198. ASSERT_EQ(0, ::listen(srv, 1));
  13199. auto server_thread = std::thread([&compressed, srv] {
  13200. sockaddr_in cli_addr{};
  13201. socklen_t cli_len = sizeof(cli_addr);
  13202. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13203. if (cli != INVALID_SOCKET) {
  13204. // Read the full HTTP request (until \r\n\r\n)
  13205. char buf[4096];
  13206. size_t total = 0;
  13207. while (total < sizeof(buf)) {
  13208. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13209. if (n <= 0) break;
  13210. total += static_cast<size_t>(n);
  13211. // Check for end of headers
  13212. if (total >= 4) {
  13213. std::string req(buf, total);
  13214. if (req.find("\r\n\r\n") != std::string::npos) break;
  13215. }
  13216. }
  13217. // Malicious response: gzip-compressed body, no Content-Length
  13218. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13219. "Content-Encoding: gzip\r\n"
  13220. "Connection: close\r\n"
  13221. "\r\n";
  13222. ::send(cli,
  13223. #ifdef _WIN32
  13224. static_cast<const char *>(response_header.c_str()),
  13225. static_cast<int>(response_header.size()),
  13226. #else
  13227. response_header.c_str(), response_header.size(),
  13228. #endif
  13229. 0);
  13230. // Send the compressed payload (small on the wire, huge when decompressed)
  13231. size_t total_sent = 0;
  13232. while (total_sent < compressed.size()) {
  13233. auto to_send = std::min(compressed.size() - total_sent,
  13234. static_cast<size_t>(64 * 1024));
  13235. auto sent =
  13236. ::send(cli,
  13237. #ifdef _WIN32
  13238. static_cast<const char *>(compressed.c_str() + total_sent),
  13239. static_cast<int>(to_send),
  13240. #else
  13241. compressed.c_str() + total_sent, to_send,
  13242. #endif
  13243. 0);
  13244. if (sent <= 0) break;
  13245. total_sent += static_cast<size_t>(sent);
  13246. }
  13247. detail::close_socket(cli);
  13248. }
  13249. });
  13250. auto se = detail::scope_exit([&] {
  13251. detail::close_socket(srv);
  13252. server_thread.join();
  13253. });
  13254. size_t total_decompressed = 0;
  13255. {
  13256. Client cli("127.0.0.1", PORT + 3);
  13257. cli.set_read_timeout(5, 0);
  13258. cli.set_decompress(true);
  13259. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13260. auto stream = cli.open_stream("GET", "/zipbomb");
  13261. ASSERT_TRUE(stream.is_valid());
  13262. char buffer[64 * 1024];
  13263. ssize_t n;
  13264. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13265. total_decompressed += static_cast<size_t>(n);
  13266. }
  13267. }
  13268. // The decompressed size must be capped by payload_max_length. Without
  13269. // protection, the client would decompress the full 10MB from a tiny
  13270. // compressed payload, enabling a zip bomb DoS attack.
  13271. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13272. << "Client decompressed " << total_decompressed
  13273. << " bytes from a gzip response. The decompressed size should be "
  13274. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13275. }
  13276. #endif
  13277. TEST(HostAndPortPropertiesTest, NoSSL) {
  13278. httplib::Client cli("www.google.com", 1234);
  13279. ASSERT_EQ("www.google.com", cli.host());
  13280. ASSERT_EQ(1234, cli.port());
  13281. }
  13282. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13283. httplib::Client cli("www.google.com:1234");
  13284. ASSERT_EQ("www.google.com", cli.host());
  13285. ASSERT_EQ(1234, cli.port());
  13286. }
  13287. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13288. // Port number that overflows int — should not crash, client becomes invalid
  13289. httplib::Client cli("http://www.google.com:99999999999999999999");
  13290. ASSERT_FALSE(cli.is_valid());
  13291. }
  13292. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13293. // Port 99999 exceeds valid range (1-65535) — should not crash
  13294. httplib::Client cli("http://www.google.com:99999");
  13295. ASSERT_FALSE(cli.is_valid());
  13296. auto res = cli.Get("/");
  13297. EXPECT_FALSE(res);
  13298. EXPECT_EQ(Error::Connection, res.error());
  13299. }
  13300. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13301. httplib::Client cli("http://user:pass@localhost:1234");
  13302. ASSERT_FALSE(cli.is_valid());
  13303. EXPECT_FALSE(cli.Get("/"));
  13304. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13305. }
  13306. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13307. httplib::Client cli("http://www.google.com:80abc");
  13308. ASSERT_FALSE(cli.is_valid());
  13309. }
  13310. #ifdef CPPHTTPLIB_SSL_ENABLED
  13311. TEST(HostAndPortPropertiesTest, SSL) {
  13312. httplib::SSLClient cli("www.google.com");
  13313. ASSERT_EQ("www.google.com", cli.host());
  13314. ASSERT_EQ(443, cli.port());
  13315. }
  13316. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13317. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13318. std::string cert;
  13319. read_file(CA_CERT_FILE, cert);
  13320. httplib::SSLClient httplib_client("www.google.com");
  13321. // Load CA store first time
  13322. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13323. // Load CA store second time (update)
  13324. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13325. // Verify client is still valid and can make connections
  13326. httplib_client.enable_server_certificate_verification(true);
  13327. auto res = httplib_client.Get("/");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. // Google may return 200 or 301 depending on various factors
  13330. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13331. res->status == StatusCode::MovedPermanently_301);
  13332. }
  13333. TEST(SSLClientTest, ServerNameIndication_Online) {
  13334. auto host = "httpbingo.org";
  13335. auto path = std::string{"/get"};
  13336. SSLClient cli(host, 443);
  13337. auto res = cli.Get(path);
  13338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13339. ASSERT_EQ(StatusCode::OK_200, res->status);
  13340. }
  13341. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13342. // Use a site that will cause SSL verification failure due to self-signed cert
  13343. SSLClient cli("self-signed.badssl.com", 443);
  13344. cli.enable_server_certificate_verification(true);
  13345. auto res = cli.Get("/");
  13346. ASSERT_TRUE(!res);
  13347. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13348. // Verify backend error is captured for SSLServerVerification
  13349. // This occurs when certificate verification fails
  13350. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13351. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13352. EXPECT_NE(0UL, res.ssl_backend_error());
  13353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13354. // For OpenSSL, ssl_error is 0 for verification errors
  13355. EXPECT_EQ(0, res.ssl_error());
  13356. #if !defined(_WIN32) || \
  13357. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13358. // On non-Windows or when Windows Schannel is disabled, the error comes
  13359. // from OpenSSL's verification
  13360. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13361. res.ssl_backend_error());
  13362. #endif
  13363. #endif
  13364. }
  13365. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13366. // Use a site where hostname doesn't match the certificate
  13367. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13368. SSLClient cli("wrong.host.badssl.com", 443);
  13369. cli.enable_server_certificate_verification(true);
  13370. cli.enable_server_hostname_verification(true);
  13371. auto res = cli.Get("/");
  13372. ASSERT_TRUE(!res);
  13373. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13374. // Verify backend error is captured for hostname verification failure
  13375. EXPECT_NE(0UL, res.ssl_backend_error());
  13376. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13377. // For OpenSSL, ssl_error is 0 for verification errors
  13378. EXPECT_EQ(0, res.ssl_error());
  13379. #if !defined(_WIN32) || \
  13380. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13381. // On non-Windows or when Windows Schannel is disabled, the error comes
  13382. // from OpenSSL's hostname verification
  13383. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13384. res.ssl_backend_error());
  13385. #endif
  13386. #endif
  13387. }
  13388. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13389. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13390. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13391. SSLClient cli("www.google.com", 443);
  13392. cli.enable_server_certificate_verification(true);
  13393. auto res = cli.Get("/");
  13394. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13395. }
  13396. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13397. SSLClient cli("www.google.com", 443);
  13398. cli.enable_server_certificate_verification(true);
  13399. cli.enable_windows_certificate_verification(false);
  13400. auto res = cli.Get("/");
  13401. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13402. }
  13403. // The server sends an intermediate cross-signed by a root Windows trusts,
  13404. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13405. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13406. SSLClient cli("accounts.spotify.com", 443);
  13407. auto res = cli.Get("/");
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13409. << " ssl_backend_error=" << res.ssl_backend_error();
  13410. }
  13411. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13412. // policy status, which no backend reports for a self-signed certificate.
  13413. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13414. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13415. ASSERT_TRUE(svr.is_valid());
  13416. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13417. auto se = detail::scope_exit([&] {
  13418. svr.stop();
  13419. t.join();
  13420. ASSERT_FALSE(svr.is_running());
  13421. });
  13422. svr.wait_until_ready();
  13423. SSLClient cli("127.0.0.1", PORT);
  13424. cli.set_connection_timeout(30);
  13425. auto res = cli.Get("/");
  13426. ASSERT_FALSE(res);
  13427. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13428. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13429. }
  13430. #endif
  13431. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13432. Client cli("https://google.com");
  13433. auto res = cli.Get("/");
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13436. }
  13437. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13438. SSLClient cli("google.com");
  13439. cli.set_ca_cert_path(CA_CERT_FILE);
  13440. auto res = cli.Get("/");
  13441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13442. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13443. }
  13444. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13445. SSLClient cli("google.com");
  13446. cli.enable_server_certificate_verification(true);
  13447. cli.set_ca_cert_path("hello");
  13448. auto res = cli.Get("/");
  13449. ASSERT_TRUE(!res);
  13450. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13451. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13452. // should be set
  13453. EXPECT_EQ(0, res.ssl_error());
  13454. // Verify backend error is captured for SSLLoadingCerts
  13455. // This error occurs when loading CA certificates fails
  13456. EXPECT_NE(0UL, res.ssl_backend_error());
  13457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13458. // OpenSSL specific error codes:
  13459. // > openssl errstr 0x80000002
  13460. // error:80000002:system library::No such file or directory
  13461. // > openssl errstr 0xA000126
  13462. // error:0A000126:SSL routines::unexpected eof while reading
  13463. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13464. res.ssl_backend_error() == 0xA000126);
  13465. #endif
  13466. }
  13467. TEST(SSLClientTest, ServerCertificateVerification4) {
  13468. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13469. ASSERT_TRUE(svr.is_valid());
  13470. svr.Get("/test", [&](const Request &, Response &res) {
  13471. res.set_content("test", "text/plain");
  13472. svr.stop();
  13473. ASSERT_TRUE(true);
  13474. });
  13475. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13476. auto se = detail::scope_exit([&] {
  13477. t.join();
  13478. ASSERT_FALSE(svr.is_running());
  13479. });
  13480. svr.wait_until_ready();
  13481. SSLClient cli("127.0.0.1", PORT);
  13482. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13483. cli.enable_server_certificate_verification(true);
  13484. cli.set_connection_timeout(30);
  13485. auto res = cli.Get("/test");
  13486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13487. ASSERT_EQ(StatusCode::OK_200, res->status);
  13488. }
  13489. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13490. std::string cert;
  13491. read_file(CA_CERT_FILE, cert);
  13492. SSLClient cli("google.com");
  13493. cli.load_ca_cert_store(cert.data(), cert.size());
  13494. const auto res = cli.Get("/");
  13495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13496. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13497. }
  13498. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13499. // clang-format off
  13500. static constexpr char cert[] =
  13501. "GlobalSign Root CA\n"
  13502. "==================\n"
  13503. "-----BEGIN CERTIFICATE-----\n"
  13504. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13505. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13506. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13507. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13508. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13509. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13510. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13511. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13512. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13513. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13514. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13515. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13516. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13517. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13518. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13519. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13520. "-----END CERTIFICATE-----\n";
  13521. // clang-format on
  13522. SSLClient cli("google.com");
  13523. cli.load_ca_cert_store(cert, sizeof(cert));
  13524. const auto res = cli.Get("/");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13527. }
  13528. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13529. SSLClient cli("www.youtube.com");
  13530. cli.set_ca_cert_path(CA_CERT_FILE);
  13531. cli.enable_server_certificate_verification(true);
  13532. cli.set_follow_location(true);
  13533. auto res = cli.Get("/");
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. ASSERT_EQ(StatusCode::OK_200, res->status);
  13536. }
  13537. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13538. SSLClient cli("wWw.YouTube.Com");
  13539. cli.set_ca_cert_path(CA_CERT_FILE);
  13540. cli.enable_server_certificate_verification(true);
  13541. cli.enable_server_hostname_verification(true);
  13542. cli.set_follow_location(true);
  13543. auto res = cli.Get("/");
  13544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13545. ASSERT_EQ(StatusCode::OK_200, res->status);
  13546. }
  13547. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13548. SSLClient cli("gOoGlE.COm");
  13549. cli.enable_server_certificate_verification(true);
  13550. cli.enable_server_hostname_verification(true);
  13551. cli.set_follow_location(true);
  13552. auto res = cli.Get("/");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. TEST(SSLClientTest, Issue2004_Online) {
  13557. Client client("https://google.com");
  13558. client.set_follow_location(true);
  13559. auto res = client.Get("/");
  13560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13561. ASSERT_EQ(StatusCode::OK_200, res->status);
  13562. auto body = res->body;
  13563. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13564. }
  13565. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13566. // Create SSLClient with invalid cert/key to make is_valid() return false
  13567. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13568. "nonexistent_key.pem");
  13569. // is_valid() should be false due to cert loading failure
  13570. ASSERT_FALSE(cli.is_valid());
  13571. auto res = cli.Get("/");
  13572. ASSERT_FALSE(res);
  13573. EXPECT_EQ(Error::SSLConnection, res.error());
  13574. }
  13575. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13576. // Test for Issue #2251: SSL error not properly reported when client cert
  13577. // and key paths are swapped or mismatched
  13578. // This simulates the scenario where user accidentally swaps the cert and key
  13579. // files
  13580. // Using client cert file as private key and vice versa (completely wrong)
  13581. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13582. // Should fail validation due to cert/key mismatch
  13583. ASSERT_FALSE(cli.is_valid());
  13584. // Attempt to make a request should fail with proper error
  13585. auto res = cli.Get("/");
  13586. ASSERT_FALSE(res);
  13587. EXPECT_EQ(Error::SSLConnection, res.error());
  13588. // SSL error should be recorded in the Result object (this is the key fix for
  13589. // Issue #2251)
  13590. auto backend_error = res.ssl_backend_error();
  13591. EXPECT_NE(0u, backend_error);
  13592. }
  13593. // Tests cert/key mismatch detection at the TLS context level
  13594. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13595. // Test that using mismatched cert/key causes connection failure.
  13596. // We verify this at the SSLClient level rather than through internal
  13597. // TLS API functions.
  13598. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13599. cli.enable_server_certificate_verification(false);
  13600. cli.set_connection_timeout(2);
  13601. // The mismatch should cause a connection or handshake error
  13602. auto res = cli.Get("/test");
  13603. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13604. // Either way, the request should fail
  13605. EXPECT_FALSE(res);
  13606. }
  13607. #endif
  13608. #if 0
  13609. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13610. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13611. ASSERT_TRUE(cli != nullptr);
  13612. cli->set_address_family(AF_INET6);
  13613. cli->set_interface("en0");
  13614. auto res = cli->Get("/get");
  13615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13616. ASSERT_EQ(StatusCode::OK_200, res->status);
  13617. }
  13618. #endif
  13619. // Client certificate tests - work with all TLS backends
  13620. #ifdef CPPHTTPLIB_SSL_ENABLED
  13621. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13622. void ClientCertPresent(
  13623. const std::string &client_cert_file,
  13624. const std::string &client_private_key_file,
  13625. const std::string &client_encrypted_private_key_pass = std::string(),
  13626. const ClientCertServerSetup &setup = nullptr) {
  13627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13628. ASSERT_TRUE(svr.is_valid());
  13629. if (setup) { setup(svr); }
  13630. svr.Get("/test", [&](const Request &req, Response &res) {
  13631. res.set_content("test", "text/plain");
  13632. auto cert = req.peer_cert();
  13633. ASSERT_TRUE(static_cast<bool>(cert));
  13634. std::string common_name = cert.subject_cn();
  13635. EXPECT_EQ("Common Name", common_name);
  13636. });
  13637. auto port = svr.bind_to_any_port(HOST);
  13638. ASSERT_LT(0, port);
  13639. thread t = thread([&]() { svr.listen_after_bind(); });
  13640. auto se = detail::scope_exit([&] {
  13641. svr.stop();
  13642. t.join();
  13643. ASSERT_FALSE(svr.is_running());
  13644. });
  13645. svr.wait_until_ready();
  13646. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13647. client_encrypted_private_key_pass);
  13648. cli.enable_server_certificate_verification(false);
  13649. cli.set_connection_timeout(30);
  13650. auto res = cli.Get("/test");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. TEST(SSLClientServerTest, ClientCertPresent) {
  13655. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13656. }
  13657. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13658. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13659. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13660. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13661. }
  13662. // Expects svr, which must require client certificates, to reject a client
  13663. // that has none
  13664. void RejectsClientWithoutCert(SSLServer &svr) {
  13665. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13666. auto port = svr.bind_to_any_port(HOST);
  13667. ASSERT_LT(0, port);
  13668. thread t = thread([&]() { svr.listen_after_bind(); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. ASSERT_FALSE(svr.is_running());
  13673. });
  13674. svr.wait_until_ready();
  13675. SSLClient cli(HOST, port);
  13676. cli.set_connection_timeout(30);
  13677. // Skip the server certificate check, so that the request fails because the
  13678. // client certificate is missing rather than because cert.pem is not trusted
  13679. cli.enable_server_certificate_verification(false);
  13680. auto res = cli.Get("/test");
  13681. ASSERT_FALSE(res);
  13682. // The server rejects the client during the handshake, or on TLS 1.3 right
  13683. // after it, which the client notices on its first write or read
  13684. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13685. res.error() == Error::Write || res.error() == Error::Read)
  13686. << to_string(res.error());
  13687. if (res.error() == Error::SSLConnection) {
  13688. EXPECT_NE(0UL, res.ssl_backend_error());
  13689. }
  13690. // A rejection noticed on the write keeps the TLS error the write hit
  13691. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13692. }
  13693. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13695. ASSERT_TRUE(svr.is_valid());
  13696. if (setup) { setup(svr); }
  13697. RejectsClientWithoutCert(svr);
  13698. }
  13699. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13700. // A server that requires client certificates must keep requiring them after
  13701. // setup changes it, and keep accepting a client that has one
  13702. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13703. ClientCertMissing(setup);
  13704. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13705. setup);
  13706. }
  13707. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13708. ClientCertStillRequired([](SSLServer &svr) {
  13709. ASSERT_TRUE(tls::set_verify_callback(
  13710. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13711. });
  13712. }
  13713. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13714. ClientCertStillRequired([](SSLServer &svr) {
  13715. ASSERT_TRUE(tls::set_verify_callback(
  13716. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13717. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13718. });
  13719. }
  13720. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13721. std::string cert_pem, key_pem, ca_pem;
  13722. read_file(SERVER_CERT_FILE, cert_pem);
  13723. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13724. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13725. ASSERT_TRUE(
  13726. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13727. }
  13728. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13730. ASSERT_TRUE(svr.is_valid());
  13731. UpdateCertsPemWithClientCA(svr);
  13732. RejectsClientWithoutCert(svr);
  13733. }
  13734. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13735. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13736. }
  13737. // A TLS error from one request must not show up in a later request's Result
  13738. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13740. ASSERT_TRUE(svr.is_valid());
  13741. svr.Get("/test", [](const Request &, Response &res) {
  13742. res.set_content("test", "text/plain");
  13743. });
  13744. auto port = svr.bind_to_any_port(HOST);
  13745. ASSERT_LT(0, port);
  13746. thread t = thread([&]() { svr.listen_after_bind(); });
  13747. auto se = detail::scope_exit([&] {
  13748. svr.stop();
  13749. t.join();
  13750. ASSERT_FALSE(svr.is_running());
  13751. });
  13752. svr.wait_until_ready();
  13753. SSLClient cli(HOST, port);
  13754. cli.set_connection_timeout(30);
  13755. cli.enable_server_hostname_verification(false);
  13756. // cert.pem is not trusted, so the handshake fails
  13757. ASSERT_FALSE(cli.Get("/test"));
  13758. cli.enable_server_certificate_verification(false);
  13759. auto res = cli.Get("/test");
  13760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13761. EXPECT_EQ(0, res.ssl_error());
  13762. EXPECT_EQ(0UL, res.ssl_backend_error());
  13763. }
  13764. // PEM memory-based constructor tests (works with all TLS backends).
  13765. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13766. // terminator after it.
  13767. void PemMemoryClientCertPresent(
  13768. const std::string &client_cert_file,
  13769. const std::string &client_private_key_file,
  13770. const std::string &client_encrypted_private_key_pass = std::string(),
  13771. bool exact_size = false) {
  13772. // Read PEM files into memory
  13773. std::string server_cert_pem, server_key_pem;
  13774. std::string client_ca_pem;
  13775. std::string client_cert_pem, client_key_pem;
  13776. read_file(SERVER_CERT_FILE, server_cert_pem);
  13777. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13778. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13779. read_file(client_cert_file, client_cert_pem);
  13780. read_file(client_private_key_file, client_key_pem);
  13781. std::list<std::vector<char>> exact_copies;
  13782. auto data = [&](const std::string &pem) -> const char * {
  13783. if (!exact_size) { return pem.c_str(); }
  13784. exact_copies.emplace_back(pem.begin(), pem.end());
  13785. return exact_copies.back().data();
  13786. };
  13787. // Create server with PEM memory
  13788. SSLServer::PemMemory server_pem = {
  13789. data(server_cert_pem),
  13790. server_cert_pem.size(),
  13791. data(server_key_pem),
  13792. server_key_pem.size(),
  13793. data(client_ca_pem),
  13794. client_ca_pem.size(),
  13795. nullptr // no password for server key
  13796. };
  13797. SSLServer svr(server_pem);
  13798. ASSERT_TRUE(svr.is_valid());
  13799. svr.Get("/test", [&](const Request &req, Response &res) {
  13800. res.set_content("test", "text/plain");
  13801. auto cert = req.peer_cert();
  13802. ASSERT_TRUE(static_cast<bool>(cert));
  13803. EXPECT_EQ("Common Name", cert.subject_cn());
  13804. });
  13805. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13806. auto se = detail::scope_exit([&] {
  13807. svr.stop();
  13808. t.join();
  13809. ASSERT_FALSE(svr.is_running());
  13810. });
  13811. svr.wait_until_ready();
  13812. // Create client with PEM memory
  13813. const char *password = client_encrypted_private_key_pass.empty()
  13814. ? nullptr
  13815. : client_encrypted_private_key_pass.c_str();
  13816. SSLClient::PemMemory client_pem = {
  13817. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13818. client_key_pem.size(), password};
  13819. SSLClient cli(HOST, PORT, client_pem);
  13820. cli.enable_server_certificate_verification(false);
  13821. cli.set_connection_timeout(30);
  13822. auto res = cli.Get("/test");
  13823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13824. ASSERT_EQ(StatusCode::OK_200, res->status);
  13825. }
  13826. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13827. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13828. }
  13829. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13830. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13831. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13832. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13833. }
  13834. // A server built from PEM memory with a client CA requires client certificates,
  13835. // also when the CA is a NUL-terminated string passed with a length of 0
  13836. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13837. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13838. read_file(SERVER_CERT_FILE, server_cert_pem);
  13839. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13840. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13841. SSLServer::PemMemory server_pem = {
  13842. server_cert_pem.c_str(),
  13843. server_cert_pem.size(),
  13844. server_key_pem.c_str(),
  13845. server_key_pem.size(),
  13846. client_ca_pem.c_str(),
  13847. client_ca_pem.size(),
  13848. nullptr // no password for server key
  13849. };
  13850. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13851. SCOPED_TRACE(client_ca_pem_len);
  13852. server_pem.client_ca_pem_len = client_ca_pem_len;
  13853. SSLServer svr(server_pem);
  13854. ASSERT_TRUE(svr.is_valid());
  13855. RejectsClientWithoutCert(svr);
  13856. }
  13857. // An empty CA fails to load instead of turning the check off
  13858. server_pem.client_ca_pem = "";
  13859. server_pem.client_ca_pem_len = 0;
  13860. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13861. }
  13862. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13863. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13864. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13865. true);
  13866. }
  13867. // A length shorter than the PEM cuts it short, so it no longer loads
  13868. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13869. std::string cert, key;
  13870. read_file(SERVER_CERT_FILE, cert);
  13871. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13872. for (auto cut_cert : {true, false}) {
  13873. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13874. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13875. SSLServer::PemMemory server_pem = {
  13876. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13877. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13878. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13879. key_len, nullptr};
  13880. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13881. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13882. key.c_str(), key_len, nullptr};
  13883. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13884. }
  13885. }
  13886. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13887. class NoListenSSLServer : public SSLServer {
  13888. public:
  13889. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13890. const char *client_ca_cert_file_path,
  13891. const char *client_ca_cert_dir_path = nullptr)
  13892. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13893. client_ca_cert_dir_path),
  13894. stop_(false) {}
  13895. std::atomic_bool stop_;
  13896. private:
  13897. bool process_and_close_socket(socket_t /*sock*/) override {
  13898. // Don't create SSL context
  13899. while (!stop_.load()) {
  13900. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13901. }
  13902. return true;
  13903. }
  13904. };
  13905. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13906. CLIENT_CA_CERT_FILE);
  13907. ASSERT_TRUE(svr.is_valid());
  13908. svr.Get("/test", [&](const Request &, Response &res) {
  13909. res.set_content("test", "text/plain");
  13910. });
  13911. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13912. auto se = detail::scope_exit([&] {
  13913. svr.stop_ = true;
  13914. svr.stop();
  13915. t.join();
  13916. ASSERT_FALSE(svr.is_running());
  13917. });
  13918. svr.wait_until_ready();
  13919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13920. cli.enable_server_certificate_verification(false);
  13921. cli.set_connection_timeout(1);
  13922. auto res = cli.Get("/test");
  13923. ASSERT_TRUE(!res);
  13924. EXPECT_EQ(Error::SSLConnection, res.error());
  13925. // Timeout results in WantRead error code (maps to backend-specific value)
  13926. EXPECT_NE(0, res.ssl_error());
  13927. }
  13928. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13929. // Test SSLServer with client certificate verification using the standard
  13930. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13932. CLIENT_CA_CERT_DIR);
  13933. ASSERT_TRUE(svr.is_valid());
  13934. svr.Get("/test", [&](const Request &req, Response &res) {
  13935. res.set_content("test", "text/plain");
  13936. auto cert = req.peer_cert();
  13937. ASSERT_TRUE(static_cast<bool>(cert));
  13938. auto common_name = cert.subject_cn();
  13939. EXPECT_EQ("Common Name", common_name);
  13940. });
  13941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13942. auto se = detail::scope_exit([&] {
  13943. svr.stop();
  13944. t.join();
  13945. ASSERT_FALSE(svr.is_running());
  13946. });
  13947. svr.wait_until_ready();
  13948. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13949. cli.enable_server_certificate_verification(false);
  13950. cli.set_connection_timeout(30);
  13951. auto res = cli.Get("/test");
  13952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13953. ASSERT_EQ(StatusCode::OK_200, res->status);
  13954. }
  13955. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13956. // Verifies that wildcard matching and exact matching work consistently
  13957. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13958. using namespace httplib::tls;
  13959. // We need a running server to test against
  13960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13961. ASSERT_TRUE(svr.is_valid());
  13962. svr.Get("/test", [](const Request &, Response &res) {
  13963. res.set_content("ok", "text/plain");
  13964. });
  13965. thread t([&]() { svr.listen(HOST, PORT); });
  13966. auto se = detail::scope_exit([&] {
  13967. svr.stop();
  13968. t.join();
  13969. });
  13970. svr.wait_until_ready();
  13971. bool verify_callback_called = false;
  13972. bool verify_result_wrong = false;
  13973. SSLClient cli(HOST, PORT);
  13974. cli.enable_server_certificate_verification(true);
  13975. cli.set_ca_cert_path(CA_CERT_FILE);
  13976. cli.set_connection_timeout(5);
  13977. // Note: Test certificate has CN="Common Name", not "localhost"
  13978. bool verify_result_cn = false;
  13979. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13980. verify_callback_called = true;
  13981. if (!ctx.cert) return false;
  13982. // Test 1: "Common Name" should match (our test server cert CN)
  13983. verify_result_cn = ctx.check_hostname("Common Name");
  13984. // Test 2: wrong hostname should not match
  13985. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13986. return true; // Accept for the purpose of this test
  13987. });
  13988. auto res = cli.Get("/test");
  13989. // The request may succeed or fail depending on cert configuration
  13990. // but the callback should have been called
  13991. ASSERT_TRUE(verify_callback_called)
  13992. << "Verify callback should have been called";
  13993. // CN="Common Name" should match our test certificate
  13994. //
  13995. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13996. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13997. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13998. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13999. // <openssl/base.h>, which is included transitively when
  14000. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14001. #if defined(OPENSSL_IS_BORINGSSL)
  14002. EXPECT_FALSE(verify_result_cn)
  14003. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14004. #else
  14005. EXPECT_TRUE(verify_result_cn)
  14006. << "verify_hostname should match 'Common Name' (certificate CN)";
  14007. #endif
  14008. // Wrong hostname should not match
  14009. EXPECT_FALSE(verify_result_wrong)
  14010. << "verify_hostname should not match 'wronghost.example.com'";
  14011. }
  14012. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14013. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14014. // X509_check_ip behavior and must hold for every backend.
  14015. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14016. using namespace httplib::tls;
  14017. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14018. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14019. ASSERT_TRUE(svr.is_valid());
  14020. svr.Get("/test", [](const Request &, Response &res) {
  14021. res.set_content("ok", "text/plain");
  14022. });
  14023. thread t([&]() { svr.listen(HOST, PORT); });
  14024. auto se = detail::scope_exit([&] {
  14025. svr.stop();
  14026. t.join();
  14027. });
  14028. svr.wait_until_ready();
  14029. bool verify_callback_called = false;
  14030. bool ip_matched_via_cn = true;
  14031. SSLClient cli(HOST, PORT);
  14032. cli.enable_server_certificate_verification(true);
  14033. cli.set_ca_cert_path(CA_CERT_FILE);
  14034. cli.set_connection_timeout(5);
  14035. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14036. verify_callback_called = true;
  14037. if (!ctx.cert) return false;
  14038. // The IP appears only in the CN, so it must NOT be accepted.
  14039. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14040. return true; // Accept for the purpose of this test
  14041. });
  14042. cli.Get("/test");
  14043. ASSERT_TRUE(verify_callback_called)
  14044. << "Verify callback should have been called";
  14045. EXPECT_FALSE(ip_matched_via_cn)
  14046. << "An IP host must not be authenticated via the certificate CN";
  14047. }
  14048. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14049. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14050. using namespace httplib::tls;
  14051. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14052. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14053. ASSERT_TRUE(svr.is_valid());
  14054. svr.Get("/test", [](const Request &, Response &res) {
  14055. res.set_content("ok", "text/plain");
  14056. });
  14057. thread t([&]() { svr.listen(HOST, PORT); });
  14058. auto se = detail::scope_exit([&] {
  14059. svr.stop();
  14060. t.join();
  14061. });
  14062. svr.wait_until_ready();
  14063. bool verify_callback_called = false;
  14064. bool san_matched = false;
  14065. bool wrong_ipv6_matched = true;
  14066. bool cn_ipv6_matched = true;
  14067. SSLClient cli(HOST, PORT);
  14068. cli.enable_server_certificate_verification(true);
  14069. cli.set_ca_cert_path(CA_CERT_FILE);
  14070. cli.set_connection_timeout(5);
  14071. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14072. verify_callback_called = true;
  14073. if (!ctx.cert) return false;
  14074. // Matches the IPv6 iPAddress SAN.
  14075. san_matched = ctx.check_hostname("2001:db8::1");
  14076. // A different IPv6 address must not match.
  14077. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14078. // "::1" lives only in the CN, so it must not be accepted.
  14079. cn_ipv6_matched = ctx.check_hostname("::1");
  14080. return true; // Accept for the purpose of this test
  14081. });
  14082. cli.Get("/test");
  14083. ASSERT_TRUE(verify_callback_called)
  14084. << "Verify callback should have been called";
  14085. EXPECT_TRUE(san_matched)
  14086. << "verify_hostname should match an IPv6 iPAddress SAN";
  14087. EXPECT_FALSE(wrong_ipv6_matched)
  14088. << "verify_hostname should not match a non-matching IPv6 address";
  14089. EXPECT_FALSE(cn_ipv6_matched)
  14090. << "An IPv6 host must not be authenticated via the certificate CN";
  14091. }
  14092. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14093. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14094. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14095. using namespace httplib::tls;
  14096. // SANs: DNS:a.zz, IP:42.46.122.122
  14097. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14098. ASSERT_TRUE(svr.is_valid());
  14099. svr.Get("/test", [](const Request &, Response &res) {
  14100. res.set_content("ok", "text/plain");
  14101. });
  14102. auto port = svr.bind_to_any_port(HOST);
  14103. thread t([&]() { svr.listen_after_bind(); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. });
  14108. svr.wait_until_ready();
  14109. bool verify_callback_called = false;
  14110. bool dns_san_matched = false;
  14111. bool ip_san_matched = false;
  14112. bool ip_matched_via_dns_san = true;
  14113. bool dns_matched_via_ip_san = true;
  14114. bool cn_matched_next_to_dns_san = true;
  14115. SSLClient cli(HOST, port);
  14116. cli.enable_server_certificate_verification(true);
  14117. cli.set_ca_cert_path(CA_CERT_FILE);
  14118. cli.set_connection_timeout(5);
  14119. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14120. verify_callback_called = true;
  14121. if (!ctx.cert) return false;
  14122. dns_san_matched = ctx.check_hostname("a.zz");
  14123. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14124. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14125. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14126. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14127. return true; // Accept for the purpose of this test
  14128. });
  14129. cli.Get("/test");
  14130. ASSERT_TRUE(verify_callback_called)
  14131. << "Verify callback should have been called";
  14132. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14133. EXPECT_TRUE(ip_san_matched)
  14134. << "verify_hostname should match an iPAddress SAN";
  14135. EXPECT_FALSE(ip_matched_via_dns_san)
  14136. << "An IP host must not be authenticated via a dNSName SAN";
  14137. EXPECT_FALSE(dns_matched_via_ip_san)
  14138. << "A DNS host must not be authenticated via an iPAddress SAN";
  14139. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14140. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14141. }
  14142. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14143. // "www.*.example.test" names one host and not every host under example.test.
  14144. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14145. using namespace httplib::tls;
  14146. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14147. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14148. ASSERT_TRUE(svr.is_valid());
  14149. svr.Get("/test", [](const Request &, Response &res) {
  14150. res.set_content("ok", "text/plain");
  14151. });
  14152. auto port = svr.bind_to_any_port(HOST);
  14153. thread t([&]() { svr.listen_after_bind(); });
  14154. auto se = detail::scope_exit([&] {
  14155. svr.stop();
  14156. t.join();
  14157. });
  14158. svr.wait_until_ready();
  14159. bool verify_callback_called = false;
  14160. bool leftmost_wildcard_matched = false;
  14161. bool wildcard_spanned_labels = true;
  14162. bool inner_wildcard_matched = true;
  14163. SSLClient cli(HOST, port);
  14164. cli.enable_server_certificate_verification(true);
  14165. cli.set_ca_cert_path(CA_CERT_FILE);
  14166. cli.set_connection_timeout(5);
  14167. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14168. verify_callback_called = true;
  14169. if (!ctx.cert) return false;
  14170. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14171. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14172. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14173. return true; // Accept for the purpose of this test
  14174. });
  14175. cli.Get("/test");
  14176. ASSERT_TRUE(verify_callback_called)
  14177. << "Verify callback should have been called";
  14178. EXPECT_TRUE(leftmost_wildcard_matched)
  14179. << "A leftmost wildcard should match a single label";
  14180. EXPECT_FALSE(wildcard_spanned_labels)
  14181. << "A wildcard label must not match more than one label";
  14182. EXPECT_FALSE(inner_wildcard_matched)
  14183. << "A wildcard outside the leftmost label must not be honoured";
  14184. }
  14185. // sans() must report each SAN entry under its own type.
  14186. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14187. using namespace httplib::tls;
  14188. // SANs: DNS:a.zz, IP:42.46.122.122
  14189. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14190. ASSERT_TRUE(svr.is_valid());
  14191. svr.Get("/test", [](const Request &, Response &res) {
  14192. res.set_content("ok", "text/plain");
  14193. });
  14194. auto port = svr.bind_to_any_port(HOST);
  14195. thread t([&]() { svr.listen_after_bind(); });
  14196. auto se = detail::scope_exit([&] {
  14197. svr.stop();
  14198. t.join();
  14199. });
  14200. svr.wait_until_ready();
  14201. bool verify_callback_called = false;
  14202. std::vector<SanEntry> sans;
  14203. SSLClient cli(HOST, port);
  14204. cli.enable_server_certificate_verification(true);
  14205. cli.set_ca_cert_path(CA_CERT_FILE);
  14206. cli.set_connection_timeout(5);
  14207. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14208. verify_callback_called = true;
  14209. if (!ctx.cert) return false;
  14210. sans = ctx.sans();
  14211. return true; // Accept for the purpose of this test
  14212. });
  14213. cli.Get("/test");
  14214. ASSERT_TRUE(verify_callback_called)
  14215. << "Verify callback should have been called";
  14216. auto has_san = [&](SanType type, const std::string &value) {
  14217. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14218. return san.type == type && san.value == value;
  14219. });
  14220. };
  14221. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14222. << "sans() should report the dNSName SAN";
  14223. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14224. << "sans() should report the iPAddress SAN";
  14225. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14226. << "sans() must not report the dNSName SAN as an address";
  14227. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14228. << "sans() must not report the iPAddress SAN as a DNS name";
  14229. }
  14230. #endif
  14231. // mbedTLS-specific callback constructor test
  14232. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14233. #ifdef CPPHTTPLIB_SSL_ENABLED
  14234. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14236. ASSERT_TRUE(svr.is_valid());
  14237. // Set up a handler to verify client certificate is present
  14238. bool client_cert_verified = false;
  14239. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14240. // Verify that client certificate was provided
  14241. client_cert_verified = true;
  14242. res.set_content("success", "text/plain");
  14243. });
  14244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14245. auto se = detail::scope_exit([&] {
  14246. svr.stop();
  14247. t.join();
  14248. ASSERT_FALSE(svr.is_running());
  14249. });
  14250. svr.wait_until_ready();
  14251. // Client with certificate
  14252. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14253. cli.enable_server_certificate_verification(false);
  14254. cli.set_connection_timeout(30);
  14255. auto res = cli.Get("/test");
  14256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14257. ASSERT_EQ(StatusCode::OK_200, res->status);
  14258. ASSERT_TRUE(client_cert_verified);
  14259. EXPECT_EQ("success", res->body);
  14260. }
  14261. #endif
  14262. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14263. // backends
  14264. #ifdef CPPHTTPLIB_SSL_ENABLED
  14265. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14266. using namespace httplib::tls;
  14267. // Test that when client CA cert file is provided,
  14268. // the server properly requests and validates client certificates
  14269. // Create a server with client authentication
  14270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14271. ASSERT_TRUE(svr.is_valid());
  14272. bool handler_called = false;
  14273. svr.Get("/test", [&](const Request &req, Response &res) {
  14274. handler_called = true;
  14275. // Verify that a client certificate was provided
  14276. auto cert = req.peer_cert();
  14277. ASSERT_TRUE(static_cast<bool>(cert));
  14278. // Get the issuer name
  14279. std::string issuer_str = cert.issuer_name();
  14280. ASSERT_FALSE(issuer_str.empty());
  14281. // The client certificate should be issued by our test CA
  14282. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14283. res.set_content("authenticated", "text/plain");
  14284. });
  14285. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. });
  14291. svr.wait_until_ready();
  14292. // Connect with a client certificate issued by the CA
  14293. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14294. cli.enable_server_certificate_verification(false);
  14295. cli.set_connection_timeout(30);
  14296. auto res = cli.Get("/test");
  14297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14298. ASSERT_EQ(StatusCode::OK_200, res->status);
  14299. ASSERT_TRUE(handler_called);
  14300. EXPECT_EQ("authenticated", res->body);
  14301. }
  14302. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14303. using namespace httplib::tls;
  14304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14305. ASSERT_TRUE(svr.is_valid());
  14306. svr.Get("/test", [](const Request &, Response &res) {
  14307. res.set_content("ok", "text/plain");
  14308. });
  14309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14310. auto se = detail::scope_exit([&] {
  14311. svr.stop();
  14312. t.join();
  14313. });
  14314. svr.wait_until_ready();
  14315. SSLClient cli(HOST, PORT);
  14316. cli.enable_server_certificate_verification(false);
  14317. cli.set_connection_timeout(30);
  14318. bool cert_checked = false;
  14319. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14320. if (ctx.cert) {
  14321. auto sans = ctx.sans();
  14322. // Test certificate may or may not have SANs - just verify the API
  14323. // works If SANs exist, verify the types are valid
  14324. for (const auto &san : sans) {
  14325. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14326. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14327. san.type == SanType::OTHER);
  14328. EXPECT_FALSE(san.value.empty());
  14329. }
  14330. cert_checked = true;
  14331. }
  14332. return true;
  14333. });
  14334. auto res = cli.Get("/test");
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. EXPECT_TRUE(cert_checked);
  14337. }
  14338. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14339. using namespace httplib::tls;
  14340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14341. ASSERT_TRUE(svr.is_valid());
  14342. svr.Get("/test", [](const Request &, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. });
  14350. svr.wait_until_ready();
  14351. SSLClient cli(HOST, PORT);
  14352. cli.enable_server_certificate_verification(false);
  14353. cli.set_connection_timeout(30);
  14354. bool validity_checked = false;
  14355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14356. if (ctx.cert) {
  14357. time_t not_before = 0, not_after = 0;
  14358. bool result = ctx.validity(not_before, not_after);
  14359. EXPECT_TRUE(result);
  14360. // Verify that not_before < now < not_after for a valid cert
  14361. time_t now = time(nullptr);
  14362. EXPECT_LT(not_before, now);
  14363. EXPECT_GT(not_after, now);
  14364. validity_checked = true;
  14365. }
  14366. return true;
  14367. });
  14368. auto res = cli.Get("/test");
  14369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14370. EXPECT_TRUE(validity_checked);
  14371. }
  14372. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14373. using namespace httplib::tls;
  14374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14375. ASSERT_TRUE(svr.is_valid());
  14376. svr.Get("/test", [](const Request &, Response &res) {
  14377. res.set_content("ok", "text/plain");
  14378. });
  14379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14380. auto se = detail::scope_exit([&] {
  14381. svr.stop();
  14382. t.join();
  14383. });
  14384. svr.wait_until_ready();
  14385. SSLClient cli(HOST, PORT);
  14386. cli.enable_server_certificate_verification(false);
  14387. cli.set_connection_timeout(30);
  14388. bool serial_checked = false;
  14389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14390. if (ctx.cert) {
  14391. std::string serial = ctx.serial();
  14392. EXPECT_FALSE(serial.empty());
  14393. // Serial should be a hex string
  14394. for (char c : serial) {
  14395. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14396. (c >= 'a' && c <= 'f'));
  14397. }
  14398. serial_checked = true;
  14399. }
  14400. return true;
  14401. });
  14402. auto res = cli.Get("/test");
  14403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14404. EXPECT_TRUE(serial_checked);
  14405. }
  14406. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14407. // Test 1: Valid CA file - no error should be recorded
  14408. {
  14409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14410. CLIENT_CA_CERT_FILE);
  14411. ASSERT_TRUE(svr.is_valid());
  14412. // With valid setup, last_ssl_error should be 0
  14413. EXPECT_EQ(0, svr.ssl_last_error());
  14414. }
  14415. // Test 2: Invalid CA file content
  14416. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14417. {
  14418. // Create a temporary file with completely invalid content
  14419. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14420. {
  14421. std::ofstream ofs(temp_invalid_ca);
  14422. ofs << "This is not a certificate file at all\n";
  14423. ofs << "Just plain text content\n";
  14424. }
  14425. // Create server with invalid CA file
  14426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14427. // Clean up temporary file
  14428. std::remove(temp_invalid_ca);
  14429. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14430. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14431. // Note: SSL_CTX_load_verify_locations typically fails first,
  14432. // but our error handling code path is still exercised
  14433. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14434. }
  14435. }
  14436. TEST(VerifyCallbackTest, VerifyContextFields) {
  14437. using namespace httplib::tls;
  14438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14439. ASSERT_TRUE(svr.is_valid());
  14440. svr.Get("/test", [](const Request &, Response &res) {
  14441. res.set_content("ok", "text/plain");
  14442. });
  14443. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14444. auto se = detail::scope_exit([&] {
  14445. svr.stop();
  14446. t.join();
  14447. });
  14448. svr.wait_until_ready();
  14449. SSLClient cli(HOST, PORT);
  14450. cli.enable_server_certificate_verification(false);
  14451. cli.set_connection_timeout(30);
  14452. int callback_count = 0;
  14453. bool saw_leaf_cert = false;
  14454. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14455. if (ctx.cert) {
  14456. callback_count++;
  14457. // We should see at least one certificate (the leaf)
  14458. std::string cn = ctx.subject_cn();
  14459. if (!cn.empty()) { saw_leaf_cert = true; }
  14460. // Verify context fields are populated
  14461. EXPECT_NE(ctx.session, nullptr);
  14462. EXPECT_GE(ctx.depth, 0);
  14463. }
  14464. return true;
  14465. });
  14466. auto res = cli.Get("/test");
  14467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14468. EXPECT_GT(callback_count, 0);
  14469. EXPECT_TRUE(saw_leaf_cert);
  14470. }
  14471. // A verifier that accepts runs alongside the built-in verification, and is the
  14472. // only check once that is turned off.
  14473. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14474. using namespace httplib::tls;
  14475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14476. ASSERT_TRUE(svr.is_valid());
  14477. svr.Get("/test", [](const Request &, Response &res) {
  14478. res.set_content("ok", "text/plain");
  14479. });
  14480. auto port = svr.bind_to_any_port(HOST);
  14481. thread t([&]() { svr.listen_after_bind(); });
  14482. auto se = detail::scope_exit([&] {
  14483. svr.stop();
  14484. t.join();
  14485. });
  14486. svr.wait_until_ready();
  14487. SSLClient cli(HOST, port);
  14488. cli.enable_server_hostname_verification(false);
  14489. auto calls = 0;
  14490. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14491. calls++;
  14492. return true;
  14493. });
  14494. // cert.pem is not trusted
  14495. auto res = cli.Get("/test");
  14496. ASSERT_FALSE(res);
  14497. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14498. EXPECT_GT(calls, 0);
  14499. cli.enable_server_certificate_verification(false);
  14500. res = cli.Get("/test");
  14501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14502. EXPECT_EQ("ok", res->body);
  14503. }
  14504. // A verifier belongs to the client that set it, not to the thread that set it.
  14505. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14506. using namespace httplib::tls;
  14507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14508. ASSERT_TRUE(svr.is_valid());
  14509. svr.Get("/test", [](const Request &, Response &res) {
  14510. res.set_content("ok", "text/plain");
  14511. });
  14512. auto port = svr.bind_to_any_port(HOST);
  14513. thread t([&]() { svr.listen_after_bind(); });
  14514. auto se = detail::scope_exit([&] {
  14515. svr.stop();
  14516. t.join();
  14517. });
  14518. svr.wait_until_ready();
  14519. auto rejecting_calls = 0;
  14520. SSLClient rejecting(HOST, port);
  14521. rejecting.enable_server_certificate_verification(false);
  14522. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14523. rejecting_calls++;
  14524. return false;
  14525. });
  14526. auto accepting_calls = 0;
  14527. SSLClient accepting(HOST, port);
  14528. accepting.enable_server_certificate_verification(false);
  14529. // Set on another thread than the requests below.
  14530. thread([&]() {
  14531. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14532. accepting_calls++;
  14533. return true;
  14534. });
  14535. }).join();
  14536. // Requested on another thread than the verifier was set on.
  14537. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14538. EXPECT_GT(rejecting_calls, 0);
  14539. auto res = accepting.Get("/test");
  14540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14541. EXPECT_GT(accepting_calls, 0);
  14542. }
  14543. // A verifier replaced while a handshake runs it lives until it returns.
  14544. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14545. using namespace httplib::tls;
  14546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14547. ASSERT_TRUE(svr.is_valid());
  14548. svr.Get("/test", [](const Request &, Response &res) {
  14549. res.set_content("ok", "text/plain");
  14550. });
  14551. auto port = svr.bind_to_any_port(HOST);
  14552. thread t([&]() { svr.listen_after_bind(); });
  14553. auto se = detail::scope_exit([&] {
  14554. svr.stop();
  14555. t.join();
  14556. });
  14557. svr.wait_until_ready();
  14558. SSLClient cli(HOST, port);
  14559. cli.enable_server_certificate_verification(false);
  14560. std::promise<void> entered;
  14561. std::promise<void> replaced;
  14562. auto replaced_future = replaced.get_future();
  14563. auto first_call = true;
  14564. // Long enough to live on the heap
  14565. std::string expected(64, 'v');
  14566. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14567. if (first_call) {
  14568. first_call = false;
  14569. entered.set_value();
  14570. replaced_future.wait();
  14571. }
  14572. return expected == std::string(64, 'v');
  14573. });
  14574. thread request([&]() {
  14575. auto res = cli.Get("/test");
  14576. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14577. });
  14578. entered.get_future().wait();
  14579. cli.set_server_certificate_verifier(
  14580. [](const VerifyContext &) { return true; });
  14581. replaced.set_value();
  14582. request.join();
  14583. }
  14584. // VerifyContext::session is the same handle the other tls:: functions take.
  14585. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14586. using namespace httplib::tls;
  14587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14588. ASSERT_TRUE(svr.is_valid());
  14589. svr.Get("/test", [](const Request &, Response &res) {
  14590. res.set_content("ok", "text/plain");
  14591. });
  14592. auto port = svr.bind_to_any_port(HOST);
  14593. thread t([&]() { svr.listen_after_bind(); });
  14594. auto se = detail::scope_exit([&] {
  14595. svr.stop();
  14596. t.join();
  14597. });
  14598. svr.wait_until_ready();
  14599. SSLClient cli(HOST, port);
  14600. cli.enable_server_certificate_verification(false);
  14601. session_t verifier_session = nullptr;
  14602. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14603. verifier_session = ctx.session;
  14604. return true;
  14605. });
  14606. session_t session_verifier_session = nullptr;
  14607. cli.set_session_verifier([&](session_t session) {
  14608. session_verifier_session = session;
  14609. return SSLVerifierResponse::NoDecisionMade;
  14610. });
  14611. auto res = cli.Get("/test");
  14612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14613. EXPECT_NE(nullptr, verifier_session);
  14614. EXPECT_EQ(session_verifier_session, verifier_session);
  14615. }
  14616. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14617. using httplib::tls::TlsError;
  14618. // Test that verify_error_to_string returns empty for success
  14619. std::string success_str = TlsError::verify_error_to_string(0);
  14620. EXPECT_TRUE(success_str.empty());
  14621. // Test that verify_error_to_string returns non-empty for error codes
  14622. // Using a common error code (certificate expired)
  14623. std::string error_str =
  14624. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14625. EXPECT_FALSE(error_str.empty());
  14626. }
  14627. TEST(SessionVerifierTest, CertificateAccepted) {
  14628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(svr.is_valid());
  14630. svr.Get("/test", [](const Request &, Response &res) {
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. });
  14638. svr.wait_until_ready();
  14639. SSLClient cli(HOST, PORT);
  14640. cli.enable_server_certificate_verification(false);
  14641. cli.set_connection_timeout(30);
  14642. bool callback_called = false;
  14643. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14644. EXPECT_NE(session, nullptr);
  14645. callback_called = true;
  14646. return SSLVerifierResponse::CertificateAccepted;
  14647. });
  14648. auto res = cli.Get("/test");
  14649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14650. EXPECT_EQ(200, res->status);
  14651. EXPECT_TRUE(callback_called);
  14652. }
  14653. TEST(SessionVerifierTest, CertificateRejected) {
  14654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14655. ASSERT_TRUE(svr.is_valid());
  14656. svr.Get("/test", [](const Request &, Response &res) {
  14657. res.set_content("ok", "text/plain");
  14658. });
  14659. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14660. auto se = detail::scope_exit([&] {
  14661. svr.stop();
  14662. t.join();
  14663. });
  14664. svr.wait_until_ready();
  14665. SSLClient cli(HOST, PORT);
  14666. cli.enable_server_certificate_verification(false);
  14667. cli.set_connection_timeout(30);
  14668. bool callback_called = false;
  14669. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14670. EXPECT_NE(session, nullptr);
  14671. callback_called = true;
  14672. return SSLVerifierResponse::CertificateRejected;
  14673. });
  14674. auto res = cli.Get("/test");
  14675. EXPECT_FALSE(res);
  14676. EXPECT_TRUE(callback_called);
  14677. }
  14678. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14680. ASSERT_TRUE(svr.is_valid());
  14681. svr.Get("/test", [](const Request &, Response &res) {
  14682. res.set_content("ok", "text/plain");
  14683. });
  14684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14685. auto se = detail::scope_exit([&] {
  14686. svr.stop();
  14687. t.join();
  14688. });
  14689. svr.wait_until_ready();
  14690. // NoDecisionMade with verification disabled should succeed (no default check)
  14691. SSLClient cli(HOST, PORT);
  14692. cli.enable_server_certificate_verification(false);
  14693. cli.set_connection_timeout(30);
  14694. bool callback_called = false;
  14695. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14696. EXPECT_NE(session, nullptr);
  14697. callback_called = true;
  14698. return SSLVerifierResponse::NoDecisionMade;
  14699. });
  14700. auto res = cli.Get("/test");
  14701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14702. EXPECT_EQ(200, res->status);
  14703. EXPECT_TRUE(callback_called);
  14704. }
  14705. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14707. ASSERT_TRUE(svr.is_valid());
  14708. svr.Get("/test", [](const Request &, Response &res) {
  14709. res.set_content("ok", "text/plain");
  14710. });
  14711. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14712. auto se = detail::scope_exit([&] {
  14713. svr.stop();
  14714. t.join();
  14715. });
  14716. svr.wait_until_ready();
  14717. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14718. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14719. // so we only check that the request fails, not whether the callback was
  14720. // called.
  14721. SSLClient cli(HOST, PORT);
  14722. cli.enable_server_certificate_verification(true);
  14723. cli.set_connection_timeout(30);
  14724. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14725. EXPECT_NE(session, nullptr);
  14726. return SSLVerifierResponse::NoDecisionMade;
  14727. });
  14728. auto res = cli.Get("/test");
  14729. EXPECT_FALSE(res);
  14730. }
  14731. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14732. // Test SSL server using PemMemory constructor with client CA certificates
  14733. // Read PEM files
  14734. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14735. read_file(SERVER_CERT_FILE, server_cert_pem);
  14736. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14737. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14738. // Create SSLServer with PemMemory constructor including client CA
  14739. SSLServer::PemMemory server_pem = {
  14740. server_cert_pem.c_str(),
  14741. server_cert_pem.size(),
  14742. server_key_pem.c_str(),
  14743. server_key_pem.size(),
  14744. client_ca_pem.c_str(),
  14745. client_ca_pem.size(),
  14746. nullptr // no password for server key
  14747. };
  14748. SSLServer svr(server_pem);
  14749. ASSERT_TRUE(svr.is_valid());
  14750. // No SSL error should be recorded for valid setup
  14751. EXPECT_EQ(0, svr.ssl_last_error());
  14752. // Set up server endpoints
  14753. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14754. res.set_content("ok", "text/plain");
  14755. });
  14756. // Start server in a thread
  14757. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14758. svr.wait_until_ready();
  14759. // Connect with client certificate (using constructor with paths)
  14760. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14761. cli.enable_server_certificate_verification(false);
  14762. auto res = cli.Get("/test-pem-ca");
  14763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14764. EXPECT_EQ(200, res->status);
  14765. EXPECT_EQ("ok", res->body);
  14766. svr.stop();
  14767. server_thread.join();
  14768. }
  14769. #endif
  14770. #ifdef _WIN32
  14771. TEST(CleanupTest, WSACleanup) {
  14772. int ret = WSACleanup();
  14773. ASSERT_EQ(0, ret);
  14774. }
  14775. #endif
  14776. #ifndef CPPHTTPLIB_SSL_ENABLED
  14777. TEST(NoSSLSupport, SimpleInterface) {
  14778. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14779. }
  14780. #endif
  14781. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14782. TEST(InvalidScheme, SimpleInterface) {
  14783. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14784. }
  14785. #endif
  14786. TEST(NoScheme, SimpleInterface) {
  14787. Client cli("yahoo.com:80");
  14788. ASSERT_TRUE(cli.is_valid());
  14789. }
  14790. TEST(SendAPI, SimpleInterface_Online) {
  14791. Client cli("http://yahoo.com");
  14792. Request req;
  14793. req.method = "GET";
  14794. req.path = "/";
  14795. auto res = cli.send(req);
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14798. }
  14799. TEST(SendAPI, WithParamsInRequest) {
  14800. Server svr;
  14801. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14802. EXPECT_TRUE(req.has_param("test"));
  14803. EXPECT_EQ("test_value", req.get_param_value("test"));
  14804. });
  14805. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14806. auto se = detail::scope_exit([&] {
  14807. svr.stop();
  14808. t.join();
  14809. ASSERT_FALSE(svr.is_running());
  14810. });
  14811. svr.wait_until_ready();
  14812. Client cli(HOST, PORT);
  14813. {
  14814. Request req;
  14815. req.method = "GET";
  14816. req.path = "/";
  14817. req.params.emplace("test", "test_value");
  14818. auto res = cli.send(req);
  14819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14820. }
  14821. {
  14822. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. }
  14825. }
  14826. TEST(ClientImplMethods, GetSocketTest) {
  14827. httplib::Server svr;
  14828. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14829. res.status = StatusCode::OK_200;
  14830. });
  14831. auto port = svr.bind_to_any_port("127.0.0.1");
  14832. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14833. auto se = detail::scope_exit([&] {
  14834. svr.stop();
  14835. thread.join();
  14836. ASSERT_FALSE(svr.is_running());
  14837. });
  14838. svr.wait_until_ready();
  14839. {
  14840. httplib::Client cli("127.0.0.1", port);
  14841. cli.set_keep_alive(true);
  14842. // Use the behavior of cpp-httplib of opening the connection
  14843. // only when the first request happens. If that changes,
  14844. // this test would be obsolete.
  14845. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14846. // This also implicitly tests the server. But other tests would fail much
  14847. // earlier than this one to be considered.
  14848. auto res = cli.Get("/");
  14849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14850. EXPECT_EQ(StatusCode::OK_200, res->status);
  14851. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14852. }
  14853. }
  14854. #ifdef CPPHTTPLIB_SSL_ENABLED
  14855. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14856. Client cli("http://yahoo.com");
  14857. auto res = cli.Get("/");
  14858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14859. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14860. cli.set_follow_location(true);
  14861. res = cli.Get("/");
  14862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14863. EXPECT_EQ(StatusCode::OK_200, res->status);
  14864. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14865. }
  14866. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14867. Client cli("https://yahoo.com");
  14868. auto res = cli.Get("/");
  14869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14870. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14871. cli.set_follow_location(true);
  14872. res = cli.Get("/");
  14873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14874. EXPECT_EQ(StatusCode::OK_200, res->status);
  14875. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14876. }
  14877. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14878. Client cli("https://yahoo.com");
  14879. auto res = cli.Get("/");
  14880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14881. ASSERT_FALSE(!res);
  14882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14883. ASSERT_FALSE(res == nullptr);
  14884. ASSERT_TRUE(res != nullptr);
  14885. EXPECT_EQ(Error::Success, res.error());
  14886. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14887. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14889. cli.set_follow_location(true);
  14890. res = cli.Get("/");
  14891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14892. EXPECT_EQ(Error::Success, res.error());
  14893. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14894. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14895. EXPECT_EQ(StatusCode::OK_200, res->status);
  14896. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14897. }
  14898. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14899. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14900. Client cli("https://cdnjs.cloudflare.com");
  14901. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14902. Headers{{"Accept-Encoding", "br"}});
  14903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14904. EXPECT_EQ(StatusCode::OK_200, res->status);
  14905. EXPECT_EQ(287630U, res->body.size());
  14906. EXPECT_EQ("application/javascript; charset=utf-8",
  14907. res->get_header_value("Content-Type"));
  14908. }
  14909. #endif
  14910. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14911. #undef REDIR_HOST // Silence compiler warning
  14912. #define REDIR_HOST "https://httpbingo.org"
  14913. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14914. Client cli(REDIR_HOST);
  14915. cli.set_follow_location(true);
  14916. auto res =
  14917. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. EXPECT_EQ(StatusCode::OK_200, res->status);
  14920. }
  14921. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14922. Client cli(REDIR_HOST);
  14923. cli.set_follow_location(true);
  14924. Params params;
  14925. params.emplace("url", "http://example.com");
  14926. params.emplace("status_code", "302");
  14927. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14929. EXPECT_EQ(StatusCode::OK_200, res->status);
  14930. }
  14931. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14932. Client cli(REDIR_HOST);
  14933. cli.set_follow_location(true);
  14934. Params params;
  14935. params.emplace("url", "http://example.com");
  14936. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14938. EXPECT_EQ(StatusCode::OK_200, res->status);
  14939. }
  14940. TEST(HttpToHttpsRedirectTest, CertFile) {
  14941. auto ssl_port = PORT + 1;
  14942. Server svr;
  14943. ASSERT_TRUE(svr.is_valid());
  14944. svr.Get("/index", [&](const Request &, Response &res) {
  14945. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14946. "/index");
  14947. svr.stop();
  14948. });
  14949. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14950. ASSERT_TRUE(ssl_svr.is_valid());
  14951. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14952. res.set_content("test", "text/plain");
  14953. ssl_svr.stop();
  14954. });
  14955. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14956. thread t2 =
  14957. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14958. auto se = detail::scope_exit([&] {
  14959. t2.join();
  14960. t.join();
  14961. ASSERT_FALSE(svr.is_running());
  14962. });
  14963. svr.wait_until_ready();
  14964. ssl_svr.wait_until_ready();
  14965. Client cli("127.0.0.1", PORT);
  14966. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14967. cli.enable_server_certificate_verification(true);
  14968. cli.set_follow_location(true);
  14969. cli.set_connection_timeout(30);
  14970. auto res = cli.Get("/index");
  14971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14972. ASSERT_EQ(StatusCode::OK_200, res->status);
  14973. }
  14974. TEST(SSLClientRedirectTest, CertFile) {
  14975. auto ssl_port = PORT + 1;
  14976. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14977. ASSERT_TRUE(ssl_svr1.is_valid());
  14978. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14979. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14980. "/index");
  14981. ssl_svr1.stop();
  14982. });
  14983. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14984. ASSERT_TRUE(ssl_svr2.is_valid());
  14985. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14986. res.set_content("test", "text/plain");
  14987. ssl_svr2.stop();
  14988. });
  14989. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14990. thread t2 =
  14991. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14992. auto se = detail::scope_exit([&] {
  14993. t2.join();
  14994. t.join();
  14995. ASSERT_FALSE(ssl_svr1.is_running());
  14996. });
  14997. ssl_svr1.wait_until_ready();
  14998. ssl_svr2.wait_until_ready();
  14999. SSLClient cli("127.0.0.1", PORT);
  15000. std::string cert;
  15001. read_file(SERVER_CERT2_FILE, cert);
  15002. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15003. cli.enable_server_certificate_verification(true);
  15004. cli.set_follow_location(true);
  15005. cli.set_connection_timeout(30);
  15006. auto res = cli.Get("/index");
  15007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15008. ASSERT_EQ(StatusCode::OK_200, res->status);
  15009. }
  15010. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15011. // another port, so the client follows it with a new client.
  15012. static Result GetThroughTlsRedirectToDifferentPort(
  15013. const std::function<void(SSLClient &)> &setup,
  15014. const char *target_cert = SERVER_CERT2_FILE,
  15015. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15016. auto ssl_port = PORT + 1;
  15017. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15018. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15019. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15020. "/index");
  15021. });
  15022. SSLServer ssl_svr2(target_cert, target_key);
  15023. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15024. res.set_content("test", "text/plain");
  15025. });
  15026. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15027. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15028. auto se = detail::scope_exit([&] {
  15029. ssl_svr2.stop();
  15030. ssl_svr1.stop();
  15031. t2.join();
  15032. t.join();
  15033. });
  15034. ssl_svr1.wait_until_ready();
  15035. ssl_svr2.wait_until_ready();
  15036. SSLClient cli("127.0.0.1", PORT);
  15037. cli.set_follow_location(true);
  15038. cli.set_connection_timeout(30);
  15039. setup(cli);
  15040. return cli.Get("/index");
  15041. }
  15042. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15043. auto calls = 0;
  15044. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15045. cli.enable_server_certificate_verification(false);
  15046. // Accept the first server only.
  15047. cli.set_session_verifier([&](tls::session_t) {
  15048. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15049. : SSLVerifierResponse::CertificateRejected;
  15050. });
  15051. });
  15052. ASSERT_FALSE(res);
  15053. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15054. EXPECT_EQ(2, calls);
  15055. }
  15056. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15057. std::string pinned;
  15058. auto res = GetThroughTlsRedirectToDifferentPort(
  15059. [&](SSLClient &cli) {
  15060. cli.enable_server_certificate_verification(false);
  15061. // Pin the first certificate seen.
  15062. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15063. if (pinned.empty()) { pinned = ctx.serial(); }
  15064. return ctx.serial() == pinned;
  15065. });
  15066. },
  15067. // A certificate other than the first server's.
  15068. SERVER_CERT_FILE);
  15069. EXPECT_FALSE(res);
  15070. EXPECT_FALSE(pinned.empty());
  15071. }
  15072. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15073. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15074. std::string cert;
  15075. read_file(SERVER_CERT2_FILE, cert);
  15076. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15077. });
  15078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15079. EXPECT_EQ(StatusCode::OK_200, res->status);
  15080. }
  15081. // The target's certificate is signed by the root CA, which the first server's
  15082. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15083. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15084. auto res = GetThroughTlsRedirectToDifferentPort(
  15085. [](SSLClient &cli) {
  15086. std::string root_ca, cert;
  15087. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15088. read_file(SERVER_CERT2_FILE, cert);
  15089. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15090. cli.load_ca_cert_store(cert.data(), cert.size());
  15091. cli.enable_server_hostname_verification(false);
  15092. },
  15093. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15095. EXPECT_EQ(StatusCode::OK_200, res->status);
  15096. }
  15097. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15098. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15099. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15100. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15101. auto res = GetThroughTlsRedirectToDifferentPort(
  15102. [](SSLClient &cli) {
  15103. std::string root_ca, cert;
  15104. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15105. read_file(SERVER_CERT2_FILE, cert);
  15106. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15107. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15108. cli.enable_server_hostname_verification(false);
  15109. },
  15110. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15111. ASSERT_FALSE(res);
  15112. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15113. }
  15114. #endif
  15115. #endif
  15116. #ifdef CPPHTTPLIB_SSL_ENABLED
  15117. // Test that set_ca_cert_store() skips system certs (consistent with
  15118. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15119. // should be trusted - system certs should NOT be loaded.
  15120. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15121. // Load a specific cert that is NOT a system CA cert
  15122. std::string cert;
  15123. read_file(SERVER_CERT2_FILE, cert);
  15124. SSLClient cli("google.com");
  15125. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15126. cli.enable_server_certificate_verification(true);
  15127. // This should FAIL because:
  15128. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15129. // 2. System certs should NOT be loaded when custom store is set
  15130. // If system certs WERE loaded, this would succeed
  15131. auto res = cli.Get("/");
  15132. ASSERT_FALSE(res);
  15133. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15134. }
  15135. // Same as above, but through the native store handle path. Regression test:
  15136. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15137. // merged system certs into the user-provided store.
  15138. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15139. std::string cert;
  15140. read_file(SERVER_CERT2_FILE, cert);
  15141. SSLClient cli("google.com");
  15142. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15143. cli.enable_server_certificate_verification(true);
  15144. auto res = cli.Get("/");
  15145. ASSERT_FALSE(res);
  15146. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15147. }
  15148. // A custom store set via the native handle must still verify a server whose
  15149. // cert it does contain.
  15150. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15151. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15152. ASSERT_TRUE(svr.is_valid());
  15153. svr.Get("/test", [&](const Request &, Response &res) {
  15154. res.set_content("test", "text/plain");
  15155. });
  15156. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. ASSERT_FALSE(svr.is_running());
  15161. });
  15162. svr.wait_until_ready();
  15163. SSLClient cli("127.0.0.1", PORT);
  15164. std::string cert;
  15165. read_file(SERVER_CERT2_FILE, cert);
  15166. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15167. cli.enable_server_certificate_verification(true);
  15168. cli.set_connection_timeout(30);
  15169. auto res = cli.Get("/test");
  15170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15171. ASSERT_EQ(StatusCode::OK_200, res->status);
  15172. }
  15173. // CA certs loaded through the universal Client must be transferred to the
  15174. // client created internally for following an HTTPS redirect. Regression test:
  15175. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15176. // the CA data for redirect transfer.
  15177. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15178. auto ssl_port = PORT + 1;
  15179. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15180. ASSERT_TRUE(ssl_svr1.is_valid());
  15181. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15182. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15183. "/index");
  15184. });
  15185. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15186. ASSERT_TRUE(ssl_svr2.is_valid());
  15187. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15188. res.set_content("test", "text/plain");
  15189. });
  15190. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15191. thread t2 =
  15192. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15193. auto se = detail::scope_exit([&] {
  15194. ssl_svr2.stop();
  15195. ssl_svr1.stop();
  15196. t2.join();
  15197. t.join();
  15198. ASSERT_FALSE(ssl_svr1.is_running());
  15199. });
  15200. ssl_svr1.wait_until_ready();
  15201. ssl_svr2.wait_until_ready();
  15202. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15203. std::string cert;
  15204. read_file(SERVER_CERT2_FILE, cert);
  15205. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15206. cli.enable_server_certificate_verification(true);
  15207. cli.set_follow_location(true);
  15208. cli.set_connection_timeout(30);
  15209. auto res = cli.Get("/index");
  15210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15211. ASSERT_EQ(StatusCode::OK_200, res->status);
  15212. }
  15213. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15214. // so a host signed by a system CA verifies even though a custom CA is set
  15215. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15216. std::string cert;
  15217. read_file(SERVER_CERT2_FILE, cert);
  15218. SSLClient cli("google.com");
  15219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15220. cli.enable_system_ca(true);
  15221. cli.enable_server_certificate_verification(true);
  15222. auto res = cli.Get("/");
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15225. }
  15226. // The custom CA remains effective when combined with the system CA
  15227. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15228. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15229. ASSERT_TRUE(svr.is_valid());
  15230. svr.Get("/test", [&](const Request &, Response &res) {
  15231. res.set_content("test", "text/plain");
  15232. });
  15233. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15234. auto se = detail::scope_exit([&] {
  15235. svr.stop();
  15236. t.join();
  15237. ASSERT_FALSE(svr.is_running());
  15238. });
  15239. svr.wait_until_ready();
  15240. SSLClient cli("127.0.0.1", PORT);
  15241. std::string cert;
  15242. read_file(SERVER_CERT2_FILE, cert);
  15243. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15244. cli.enable_system_ca(true);
  15245. cli.enable_server_certificate_verification(true);
  15246. cli.set_connection_timeout(30);
  15247. auto res = cli.Get("/test");
  15248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15249. ASSERT_EQ(StatusCode::OK_200, res->status);
  15250. }
  15251. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15252. // skip chain verification entirely (only the certificate identity was
  15253. // checked), so a server presenting an untrusted certificate with a matching
  15254. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15255. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15256. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15257. ASSERT_TRUE(svr.is_valid());
  15258. svr.Get("/test", [&](const Request &, Response &res) {
  15259. res.set_content("test", "text/plain");
  15260. });
  15261. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15262. auto se = detail::scope_exit([&] {
  15263. svr.stop();
  15264. t.join();
  15265. ASSERT_FALSE(svr.is_running());
  15266. });
  15267. svr.wait_until_ready();
  15268. SSLClient cli("127.0.0.1", PORT);
  15269. std::string cert;
  15270. // A trusted CA that did not sign the server certificate. The server cert
  15271. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15272. // this connection.
  15273. read_file(CLIENT_CA_CERT_FILE, cert);
  15274. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15275. cli.enable_server_certificate_verification(true);
  15276. cli.set_connection_timeout(30);
  15277. auto res = cli.Get("/test");
  15278. ASSERT_FALSE(res);
  15279. }
  15280. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15281. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15282. // CA that failed to come through fails verification instead of trusting them.
  15283. // (wolfSSL does not list the system CAs it loaded.)
  15284. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15285. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15286. ASSERT_TRUE(svr.is_valid());
  15287. auto port = svr.bind_to_any_port("127.0.0.1");
  15288. ASSERT_LT(0, port);
  15289. thread t = thread([&] { svr.listen_after_bind(); });
  15290. auto se = detail::scope_exit([&] {
  15291. svr.stop();
  15292. t.join();
  15293. ASSERT_FALSE(svr.is_running());
  15294. });
  15295. svr.wait_until_ready();
  15296. // The CAs a client trusts once its first request has loaded them
  15297. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15298. Client cli("https://127.0.0.1:" + std::to_string(port));
  15299. setup(cli);
  15300. cli.Get("/");
  15301. return tls::get_ca_names(cli.tls_context()).size();
  15302. };
  15303. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15304. EXPECT_EQ(0u,
  15305. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15306. }
  15307. #endif
  15308. // enable_system_ca(false) prevents system CA loading entirely
  15309. TEST(SSLClientTest, DisableSystemCa_Online) {
  15310. SSLClient cli("google.com");
  15311. cli.enable_system_ca(false);
  15312. cli.enable_server_certificate_verification(true);
  15313. auto res = cli.Get("/");
  15314. ASSERT_FALSE(res);
  15315. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15316. // itself when the CA chain is empty
  15317. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15318. res.error() == Error::SSLConnection);
  15319. }
  15320. // The universal Client forwards enable_system_ca()
  15321. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15322. std::string cert;
  15323. read_file(SERVER_CERT2_FILE, cert);
  15324. Client cli("https://google.com");
  15325. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15326. cli.enable_system_ca(true);
  15327. cli.enable_server_certificate_verification(true);
  15328. auto res = cli.Get("/");
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15331. }
  15332. // The system CA policy must carry over to the client created internally for
  15333. // following a cross-host HTTPS redirect
  15334. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15335. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(svr.is_valid());
  15337. svr.Get("/index", [&](const Request &, Response &res) {
  15338. res.set_redirect("https://www.google.com/");
  15339. });
  15340. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15341. auto se = detail::scope_exit([&] {
  15342. svr.stop();
  15343. t.join();
  15344. ASSERT_FALSE(svr.is_running());
  15345. });
  15346. svr.wait_until_ready();
  15347. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15348. std::string cert;
  15349. read_file(SERVER_CERT2_FILE, cert);
  15350. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15351. cli.enable_system_ca(true);
  15352. cli.enable_server_certificate_verification(true);
  15353. cli.set_follow_location(true);
  15354. cli.set_connection_timeout(30);
  15355. // Receiving any response proves the redirect client completed the TLS
  15356. // handshake with a system-CA-signed host
  15357. auto res = cli.Get("/index");
  15358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15359. }
  15360. TEST(MultipartFormDataTest, LargeData) {
  15361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15362. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15363. const ContentReader &content_reader) {
  15364. if (req.is_multipart_form_data()) {
  15365. std::vector<FormData> items;
  15366. content_reader(
  15367. [&](const FormData &file) {
  15368. items.push_back(file);
  15369. return true;
  15370. },
  15371. [&](const char *data, size_t data_length) {
  15372. items.back().content.append(data, data_length);
  15373. return true;
  15374. });
  15375. EXPECT_TRUE(std::string(items[0].name) == "document");
  15376. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15377. EXPECT_TRUE(items[0].filename == "2MB_data");
  15378. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15379. EXPECT_TRUE(items[1].name == "hello");
  15380. EXPECT_TRUE(items[1].content == "world");
  15381. EXPECT_TRUE(items[1].filename == "");
  15382. EXPECT_TRUE(items[1].content_type == "");
  15383. } else {
  15384. std::string body;
  15385. content_reader([&](const char *data, size_t data_length) {
  15386. body.append(data, data_length);
  15387. return true;
  15388. });
  15389. }
  15390. });
  15391. auto port = svr.bind_to_any_port(HOST);
  15392. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15393. auto se = detail::scope_exit([&] {
  15394. svr.stop();
  15395. t.join();
  15396. ASSERT_FALSE(svr.is_running());
  15397. });
  15398. svr.wait_until_ready();
  15399. {
  15400. std::string data(1024 * 1024 * 2, '.');
  15401. std::stringstream buffer;
  15402. buffer << data;
  15403. SSLClient cli(HOST, port);
  15404. cli.enable_server_certificate_verification(false);
  15405. UploadFormDataItems items{
  15406. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15407. {"hello", "world", "", ""},
  15408. };
  15409. auto res = cli.Post("/post", items);
  15410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15411. ASSERT_EQ(StatusCode::OK_200, res->status);
  15412. }
  15413. }
  15414. TEST(MultipartFormDataTest, DataProviderItems) {
  15415. std::random_device seed_gen;
  15416. std::mt19937 random(seed_gen());
  15417. std::string rand1;
  15418. rand1.resize(1000);
  15419. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15420. std::string rand2;
  15421. rand2.resize(3000);
  15422. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15424. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15425. const ContentReader &content_reader) {
  15426. ASSERT_FALSE(req.is_multipart_form_data());
  15427. std::string body;
  15428. content_reader([&](const char *data, size_t data_length) {
  15429. body.append(data, data_length);
  15430. return true;
  15431. });
  15432. EXPECT_EQ(body, "");
  15433. });
  15434. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15435. const ContentReader &content_reader) {
  15436. ASSERT_TRUE(req.is_multipart_form_data());
  15437. std::vector<FormData> items;
  15438. content_reader(
  15439. [&](const FormData &file) {
  15440. items.push_back(file);
  15441. return true;
  15442. },
  15443. [&](const char *data, size_t data_length) {
  15444. items.back().content.append(data, data_length);
  15445. return true;
  15446. });
  15447. ASSERT_TRUE(items.size() == 2);
  15448. EXPECT_EQ(std::string(items[0].name), "name1");
  15449. EXPECT_EQ(items[0].content, "Testing123");
  15450. EXPECT_EQ(items[0].filename, "filename1");
  15451. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15452. EXPECT_EQ(items[1].name, "name2");
  15453. EXPECT_EQ(items[1].content, "Testing456");
  15454. EXPECT_EQ(items[1].filename, "");
  15455. EXPECT_EQ(items[1].content_type, "");
  15456. });
  15457. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15458. const ContentReader &content_reader) {
  15459. ASSERT_TRUE(req.is_multipart_form_data());
  15460. std::vector<FormData> items;
  15461. content_reader(
  15462. [&](const FormData &file) {
  15463. items.push_back(file);
  15464. return true;
  15465. },
  15466. [&](const char *data, size_t data_length) {
  15467. items.back().content.append(data, data_length);
  15468. return true;
  15469. });
  15470. ASSERT_TRUE(items.size() == 2);
  15471. EXPECT_EQ(items[0].name, "name3");
  15472. EXPECT_EQ(items[0].content, rand1);
  15473. EXPECT_EQ(items[0].filename, "filename3");
  15474. EXPECT_EQ(items[0].content_type, "");
  15475. EXPECT_EQ(items[1].name, "name4");
  15476. EXPECT_EQ(items[1].content, rand2);
  15477. EXPECT_EQ(items[1].filename, "filename4");
  15478. EXPECT_EQ(items[1].content_type, "");
  15479. });
  15480. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15481. const ContentReader &content_reader) {
  15482. ASSERT_TRUE(req.is_multipart_form_data());
  15483. std::vector<FormData> items;
  15484. content_reader(
  15485. [&](const FormData &file) {
  15486. items.push_back(file);
  15487. return true;
  15488. },
  15489. [&](const char *data, size_t data_length) {
  15490. items.back().content.append(data, data_length);
  15491. return true;
  15492. });
  15493. ASSERT_TRUE(items.size() == 4);
  15494. EXPECT_EQ(std::string(items[0].name), "name1");
  15495. EXPECT_EQ(items[0].content, "Testing123");
  15496. EXPECT_EQ(items[0].filename, "filename1");
  15497. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15498. EXPECT_EQ(items[1].name, "name2");
  15499. EXPECT_EQ(items[1].content, "Testing456");
  15500. EXPECT_EQ(items[1].filename, "");
  15501. EXPECT_EQ(items[1].content_type, "");
  15502. EXPECT_EQ(items[2].name, "name3");
  15503. EXPECT_EQ(items[2].content, rand1);
  15504. EXPECT_EQ(items[2].filename, "filename3");
  15505. EXPECT_EQ(items[2].content_type, "");
  15506. EXPECT_EQ(items[3].name, "name4");
  15507. EXPECT_EQ(items[3].content, rand2);
  15508. EXPECT_EQ(items[3].filename, "filename4");
  15509. EXPECT_EQ(items[3].content_type, "");
  15510. });
  15511. auto port = svr.bind_to_any_port("localhost");
  15512. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15513. auto se = detail::scope_exit([&] {
  15514. svr.stop();
  15515. t.join();
  15516. ASSERT_FALSE(svr.is_running());
  15517. });
  15518. svr.wait_until_ready();
  15519. {
  15520. SSLClient cli("localhost", port);
  15521. cli.enable_server_certificate_verification(false);
  15522. UploadFormDataItems items{
  15523. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15524. {"name2", "Testing456", "", ""}, // not a file
  15525. };
  15526. {
  15527. auto res = cli.Post("/post-none", {}, {}, {});
  15528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15529. ASSERT_EQ(StatusCode::OK_200, res->status);
  15530. }
  15531. FormDataProviderItems providers;
  15532. {
  15533. auto res =
  15534. cli.Post("/post-items", {}, items, providers); // empty providers
  15535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15536. ASSERT_EQ(StatusCode::OK_200, res->status);
  15537. }
  15538. providers.push_back({"name3",
  15539. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15540. // test the offset is given correctly at each step
  15541. if (!offset)
  15542. sink.os.write(rand1.data(), 30);
  15543. else if (offset == 30)
  15544. sink.os.write(rand1.data() + 30, 300);
  15545. else if (offset == 330)
  15546. sink.os.write(rand1.data() + 330, 670);
  15547. else if (offset == rand1.size())
  15548. sink.done();
  15549. return true;
  15550. },
  15551. "filename3",
  15552. {}});
  15553. providers.push_back({"name4",
  15554. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15555. // test the offset is given correctly at each step
  15556. if (!offset)
  15557. sink.os.write(rand2.data(), 2000);
  15558. else if (offset == 2000)
  15559. sink.os.write(rand2.data() + 2000, 1);
  15560. else if (offset == 2001)
  15561. sink.os.write(rand2.data() + 2001, 999);
  15562. else if (offset == rand2.size())
  15563. sink.done();
  15564. return true;
  15565. },
  15566. "filename4",
  15567. {}});
  15568. {
  15569. auto res = cli.Post("/post-providers", {}, {}, providers);
  15570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15571. ASSERT_EQ(StatusCode::OK_200, res->status);
  15572. }
  15573. {
  15574. auto res = cli.Post("/post-both", {}, items, providers);
  15575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15576. ASSERT_EQ(StatusCode::OK_200, res->status);
  15577. }
  15578. }
  15579. }
  15580. TEST(MultipartFormDataTest, BadHeader) {
  15581. Server svr;
  15582. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15583. res.set_content("ok", "text/plain");
  15584. });
  15585. thread t = thread([&] { svr.listen(HOST, PORT); });
  15586. auto se = detail::scope_exit([&] {
  15587. svr.stop();
  15588. t.join();
  15589. ASSERT_FALSE(svr.is_running());
  15590. });
  15591. svr.wait_until_ready();
  15592. const std::string body =
  15593. "This is the preamble. It is to be ignored, though it\r\n"
  15594. "is a handy place for composition agents to include an\r\n"
  15595. "explanatory note to non-MIME conformant readers.\r\n"
  15596. "\r\n"
  15597. "\r\n"
  15598. "--simple boundary\r\n"
  15599. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15600. ": BAD...\r\n"
  15601. "\r\n"
  15602. "value1\r\n"
  15603. "--simple boundary\r\n"
  15604. "Content-Disposition: form-data; name=\"field2\"; "
  15605. "filename=\"example.txt\"\r\n"
  15606. "\r\n"
  15607. "value2\r\n"
  15608. "--simple boundary--\r\n"
  15609. "This is the epilogue. It is also to be ignored.\r\n";
  15610. std::string content_type =
  15611. R"(multipart/form-data; boundary="simple boundary")";
  15612. Client cli(HOST, PORT);
  15613. auto res = cli.Post("/post", body, content_type.c_str());
  15614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15616. }
  15617. TEST(MultipartFormDataTest, WithPreamble) {
  15618. Server svr;
  15619. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15620. res.set_content("ok", "text/plain");
  15621. });
  15622. thread t = thread([&] { svr.listen(HOST, PORT); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. t.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. const std::string body =
  15630. "This is the preamble. It is to be ignored, though it\r\n"
  15631. "is a handy place for composition agents to include an\r\n"
  15632. "explanatory note to non-MIME conformant readers.\r\n"
  15633. "\r\n"
  15634. "\r\n"
  15635. "--simple boundary\r\n"
  15636. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15637. "\r\n"
  15638. "value1\r\n"
  15639. "--simple boundary\r\n"
  15640. "Content-Disposition: form-data; name=\"field2\"; "
  15641. "filename=\"example.txt\"\r\n"
  15642. "\r\n"
  15643. "value2\r\n"
  15644. "--simple boundary--\r\n"
  15645. "This is the epilogue. It is also to be ignored.\r\n";
  15646. std::string content_type =
  15647. R"(multipart/form-data; boundary="simple boundary")";
  15648. Client cli(HOST, PORT);
  15649. auto res = cli.Post("/post", body, content_type.c_str());
  15650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15651. EXPECT_EQ(StatusCode::OK_200, res->status);
  15652. }
  15653. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15655. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15656. const ContentReader &content_reader) {
  15657. if (req.is_multipart_form_data()) {
  15658. std::vector<FormData> items;
  15659. content_reader(
  15660. [&](const FormData &file) {
  15661. items.push_back(file);
  15662. return true;
  15663. },
  15664. [&](const char *data, size_t data_length) {
  15665. items.back().content.append(data, data_length);
  15666. return true;
  15667. });
  15668. EXPECT_TRUE(std::string(items[0].name) == "document");
  15669. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15670. EXPECT_TRUE(items[0].filename == "2MB_data");
  15671. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15672. EXPECT_TRUE(items[1].name == "hello");
  15673. EXPECT_TRUE(items[1].content == "world");
  15674. EXPECT_TRUE(items[1].filename == "");
  15675. EXPECT_TRUE(items[1].content_type == "");
  15676. } else {
  15677. std::string body;
  15678. content_reader([&](const char *data, size_t data_length) {
  15679. body.append(data, data_length);
  15680. return true;
  15681. });
  15682. }
  15683. });
  15684. auto port = svr.bind_to_any_port("localhost");
  15685. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15686. auto se = detail::scope_exit([&] {
  15687. svr.stop();
  15688. t.join();
  15689. ASSERT_FALSE(svr.is_running());
  15690. });
  15691. svr.wait_until_ready();
  15692. {
  15693. std::string data(1024 * 1024 * 2, '.');
  15694. std::stringstream buffer;
  15695. buffer << data;
  15696. SSLClient cli("localhost", port);
  15697. cli.enable_server_certificate_verification(false);
  15698. UploadFormDataItems items{
  15699. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15700. {"hello", "world", "", ""},
  15701. };
  15702. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15704. ASSERT_EQ(StatusCode::OK_200, res->status);
  15705. }
  15706. }
  15707. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15708. std::string data(1024 * 1024 * 2, '&');
  15709. std::stringstream buffer;
  15710. buffer << data;
  15711. Client cli("https://localhost:8080");
  15712. UploadFormDataItems items{
  15713. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15714. {"hello", "world", "", ""},
  15715. };
  15716. for (const char &c : " \t\r\n") {
  15717. auto res =
  15718. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15719. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15720. ASSERT_FALSE(res);
  15721. }
  15722. }
  15723. TEST(MultipartFormDataTest, PutFormData) {
  15724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15725. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15726. const ContentReader &content_reader) {
  15727. if (req.is_multipart_form_data()) {
  15728. std::vector<FormData> items;
  15729. content_reader(
  15730. [&](const FormData &file) {
  15731. items.push_back(file);
  15732. return true;
  15733. },
  15734. [&](const char *data, size_t data_length) {
  15735. items.back().content.append(data, data_length);
  15736. return true;
  15737. });
  15738. EXPECT_TRUE(std::string(items[0].name) == "document");
  15739. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15740. EXPECT_TRUE(items[0].filename == "2MB_data");
  15741. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15742. EXPECT_TRUE(items[1].name == "hello");
  15743. EXPECT_TRUE(items[1].content == "world");
  15744. EXPECT_TRUE(items[1].filename == "");
  15745. EXPECT_TRUE(items[1].content_type == "");
  15746. } else {
  15747. std::string body;
  15748. content_reader([&](const char *data, size_t data_length) {
  15749. body.append(data, data_length);
  15750. return true;
  15751. });
  15752. }
  15753. });
  15754. auto port = svr.bind_to_any_port("localhost");
  15755. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15756. auto se = detail::scope_exit([&] {
  15757. svr.stop();
  15758. t.join();
  15759. ASSERT_FALSE(svr.is_running());
  15760. });
  15761. svr.wait_until_ready();
  15762. {
  15763. std::string data(1024 * 1024 * 2, '&');
  15764. std::stringstream buffer;
  15765. buffer << data;
  15766. SSLClient cli("localhost", port);
  15767. cli.enable_server_certificate_verification(false);
  15768. UploadFormDataItems items{
  15769. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15770. {"hello", "world", "", ""},
  15771. };
  15772. auto res = cli.Put("/put", items);
  15773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15774. ASSERT_EQ(StatusCode::OK_200, res->status);
  15775. }
  15776. }
  15777. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15779. svr.Put("/put_customboundary",
  15780. [&](const Request &req, const Response & /*res*/,
  15781. const ContentReader &content_reader) {
  15782. if (req.is_multipart_form_data()) {
  15783. std::vector<FormData> items;
  15784. content_reader(
  15785. [&](const FormData &file) {
  15786. items.push_back(file);
  15787. return true;
  15788. },
  15789. [&](const char *data, size_t data_length) {
  15790. items.back().content.append(data, data_length);
  15791. return true;
  15792. });
  15793. EXPECT_TRUE(std::string(items[0].name) == "document");
  15794. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15795. EXPECT_TRUE(items[0].filename == "2MB_data");
  15796. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15797. EXPECT_TRUE(items[1].name == "hello");
  15798. EXPECT_TRUE(items[1].content == "world");
  15799. EXPECT_TRUE(items[1].filename == "");
  15800. EXPECT_TRUE(items[1].content_type == "");
  15801. } else {
  15802. std::string body;
  15803. content_reader([&](const char *data, size_t data_length) {
  15804. body.append(data, data_length);
  15805. return true;
  15806. });
  15807. }
  15808. });
  15809. auto port = svr.bind_to_any_port("localhost");
  15810. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15811. auto se = detail::scope_exit([&] {
  15812. svr.stop();
  15813. t.join();
  15814. ASSERT_FALSE(svr.is_running());
  15815. });
  15816. svr.wait_until_ready();
  15817. {
  15818. std::string data(1024 * 1024 * 2, '&');
  15819. std::stringstream buffer;
  15820. buffer << data;
  15821. SSLClient cli("localhost", port);
  15822. cli.enable_server_certificate_verification(false);
  15823. UploadFormDataItems items{
  15824. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15825. {"hello", "world", "", ""},
  15826. };
  15827. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15829. ASSERT_EQ(StatusCode::OK_200, res->status);
  15830. }
  15831. }
  15832. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15833. std::string data(1024 * 1024 * 2, '&');
  15834. std::stringstream buffer;
  15835. buffer << data;
  15836. Client cli("https://localhost:8080");
  15837. cli.enable_server_certificate_verification(false);
  15838. UploadFormDataItems items{
  15839. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15840. {"hello", "world", "", ""},
  15841. };
  15842. for (const char &c : " \t\r\n") {
  15843. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15844. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15845. ASSERT_FALSE(res);
  15846. }
  15847. }
  15848. TEST(MultipartFormDataTest, AlternateFilename) {
  15849. auto handled = false;
  15850. Server svr;
  15851. svr.Post("/test", [&](const Request &req, Response &res) {
  15852. ASSERT_EQ(2u, req.form.files.size());
  15853. ASSERT_EQ(1u, req.form.fields.size());
  15854. // Test files
  15855. const auto &file1 = req.form.get_file("file1");
  15856. ASSERT_EQ("file1", file1.name);
  15857. ASSERT_EQ("A.txt", file1.filename);
  15858. ASSERT_EQ("text/plain", file1.content_type);
  15859. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15860. const auto &file2 = req.form.get_file("file2");
  15861. ASSERT_EQ("file2", file2.name);
  15862. ASSERT_EQ("a.html", file2.filename);
  15863. ASSERT_EQ("text/html", file2.content_type);
  15864. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15865. file2.content);
  15866. // Test text field
  15867. const auto &text = req.form.get_field("text");
  15868. ASSERT_EQ("text default", text);
  15869. res.set_content("ok", "text/plain");
  15870. handled = true;
  15871. });
  15872. thread t = thread([&] { svr.listen(HOST, PORT); });
  15873. auto se = detail::scope_exit([&] {
  15874. svr.stop();
  15875. t.join();
  15876. ASSERT_FALSE(svr.is_running());
  15877. ASSERT_TRUE(handled);
  15878. });
  15879. svr.wait_until_ready();
  15880. auto req = "POST /test HTTP/1.1\r\n"
  15881. "Host: localhost\r\n"
  15882. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15883. "Content-Length: 399\r\n"
  15884. "\r\n"
  15885. "----------\r\n"
  15886. "Content-Disposition: form-data; name=\"text\"\r\n"
  15887. "\r\n"
  15888. "text default\r\n"
  15889. "----------\r\n"
  15890. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15891. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15892. "Content-Type: text/plain\r\n"
  15893. "\r\n"
  15894. "Content of a.txt.\r\n"
  15895. "\r\n"
  15896. "----------\r\n"
  15897. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15898. "\"a.html\"\r\n"
  15899. "Content-Type: text/html\r\n"
  15900. "\r\n"
  15901. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15902. "\r\n"
  15903. "------------\r\n";
  15904. ASSERT_TRUE(send_request(1, req));
  15905. }
  15906. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15907. auto handled = false;
  15908. Server svr;
  15909. svr.Post("/test", [&](const Request &req, Response &res) {
  15910. // Case-insensitive "utf-8''" prefix with a long value
  15911. const auto &file = req.form.get_file("file1");
  15912. ASSERT_EQ("file1", file.name);
  15913. // 8000 chars exercises both the Content-Disposition parser and the
  15914. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15915. // Prior to the fix, std::regex_match on this header would cause O(N)
  15916. // stack recursion in libstdc++, leading to SIGSEGV.
  15917. std::string expected_filename(8000, 'A');
  15918. ASSERT_EQ(expected_filename, file.filename);
  15919. res.set_content("ok", "text/plain");
  15920. handled = true;
  15921. });
  15922. thread t = thread([&] { svr.listen(HOST, PORT); });
  15923. auto se = detail::scope_exit([&] {
  15924. svr.stop();
  15925. t.join();
  15926. ASSERT_FALSE(svr.is_running());
  15927. ASSERT_TRUE(handled);
  15928. });
  15929. svr.wait_until_ready();
  15930. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15931. // Regression test for GHSA-qq6v-r583-3h69
  15932. std::string long_filename(8000, 'A');
  15933. std::string body = "----------\r\n"
  15934. "Content-Disposition: form-data; name=\"file1\"; "
  15935. "filename*=\"Utf-8''" +
  15936. long_filename +
  15937. "\"\r\n"
  15938. "\r\n"
  15939. "hello\r\n"
  15940. "------------\r\n";
  15941. auto req = "POST /test HTTP/1.1\r\n"
  15942. "Host: localhost\r\n"
  15943. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15944. "Content-Length: " +
  15945. std::to_string(body.size()) + "\r\n\r\n" + body;
  15946. ASSERT_TRUE(send_request(1, req));
  15947. }
  15948. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15949. auto handled = false;
  15950. Server svr;
  15951. svr.Post("/test", [&](const Request &req, Response &) {
  15952. ASSERT_EQ(2u, req.form.fields.size());
  15953. const auto &text1 = req.form.get_field("text1");
  15954. ASSERT_EQ("text1", text1);
  15955. const auto &text2 = req.form.get_field("text2");
  15956. ASSERT_EQ("text2", text2);
  15957. handled = true;
  15958. });
  15959. thread t = thread([&] { svr.listen(HOST, PORT); });
  15960. auto se = detail::scope_exit([&] {
  15961. svr.stop();
  15962. t.join();
  15963. ASSERT_FALSE(svr.is_running());
  15964. ASSERT_TRUE(handled);
  15965. });
  15966. svr.wait_until_ready();
  15967. auto req = "POST /test HTTP/1.1\r\n"
  15968. "Host: localhost\r\n"
  15969. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15970. "Content-Length: 146\r\n"
  15971. "\r\n----------\r\n"
  15972. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15973. "\r\n"
  15974. "text1"
  15975. "\r\n----------\r\n"
  15976. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15977. "\r\n"
  15978. "text2"
  15979. "\r\n------------";
  15980. std::string response;
  15981. ASSERT_TRUE(send_request(1, req, &response));
  15982. ASSERT_EQ("200", response.substr(9, 3));
  15983. }
  15984. TEST(MultipartFormDataTest, ContentLength) {
  15985. auto handled = false;
  15986. Server svr;
  15987. svr.Post("/test", [&](const Request &req, Response &) {
  15988. ASSERT_EQ(2u, req.form.fields.size());
  15989. const auto &text1 = req.form.get_field("text1");
  15990. ASSERT_EQ("text1", text1);
  15991. const auto &text2 = req.form.get_field("text2");
  15992. ASSERT_EQ("text2", text2);
  15993. handled = true;
  15994. });
  15995. thread t = thread([&] { svr.listen(HOST, PORT); });
  15996. auto se = detail::scope_exit([&] {
  15997. svr.stop();
  15998. t.join();
  15999. ASSERT_FALSE(svr.is_running());
  16000. ASSERT_TRUE(handled);
  16001. });
  16002. svr.wait_until_ready();
  16003. auto req = "POST /test HTTP/1.1\r\n"
  16004. "Host: localhost\r\n"
  16005. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16006. "Content-Length: 167\r\n"
  16007. "\r\n----------\r\n"
  16008. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16009. "Content-Length: 5\r\n"
  16010. "\r\n"
  16011. "text1"
  16012. "\r\n----------\r\n"
  16013. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16014. "\r\n"
  16015. "text2"
  16016. "\r\n------------\r\n";
  16017. std::string response;
  16018. ASSERT_TRUE(send_request(1, req, &response));
  16019. ASSERT_EQ("200", response.substr(9, 3));
  16020. }
  16021. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16022. auto handled = false;
  16023. Server svr;
  16024. svr.Post("/test", [&](const Request &req, Response &) {
  16025. ASSERT_EQ(2u, req.form.fields.size());
  16026. const auto &text1 = req.form.get_field("text1");
  16027. ASSERT_EQ("text1", text1);
  16028. // TODO: Add header access for text fields if needed
  16029. const auto &text2 = req.form.get_field("text2");
  16030. ASSERT_EQ("text2", text2);
  16031. // TODO: Header access for text fields needs to be implemented
  16032. // auto &headers = it->second.headers;
  16033. // ASSERT_EQ(3U, headers.size());
  16034. // auto custom_header = headers.find("x-whatever");
  16035. // ASSERT_TRUE(custom_header != headers.end());
  16036. // ASSERT_NE("customvalue", custom_header->second);
  16037. // ASSERT_EQ("CustomValue", custom_header->second);
  16038. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16039. handled = true;
  16040. });
  16041. thread t = thread([&] { svr.listen(HOST, PORT); });
  16042. auto se = detail::scope_exit([&] {
  16043. svr.stop();
  16044. t.join();
  16045. ASSERT_FALSE(svr.is_running());
  16046. ASSERT_TRUE(handled);
  16047. });
  16048. svr.wait_until_ready();
  16049. auto req = "POST /test HTTP/1.1\r\n"
  16050. "Host: localhost\r\n"
  16051. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16052. "Content-Length: 232\r\n"
  16053. "\r\n----------\r\n"
  16054. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16055. "Content-Length: 5\r\n"
  16056. "X-Test: 1\r\n"
  16057. "\r\n"
  16058. "text1"
  16059. "\r\n----------\r\n"
  16060. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16061. "Content-Type: text/plain\r\n"
  16062. "X-Whatever: CustomValue\r\n"
  16063. "\r\n"
  16064. "text2"
  16065. "\r\n------------\r\n"
  16066. "That should be disregarded. Not even read";
  16067. std::string response;
  16068. ASSERT_TRUE(send_request(1, req, &response));
  16069. ASSERT_EQ("200", response.substr(9, 3));
  16070. }
  16071. TEST(MultipartFormDataTest, LargeHeader) {
  16072. auto handled = false;
  16073. Server svr;
  16074. svr.Post("/test", [&](const Request &req, Response &) {
  16075. ASSERT_EQ(1u, req.form.fields.size());
  16076. const auto &text = req.form.get_field("name1");
  16077. ASSERT_EQ("text1", text);
  16078. handled = true;
  16079. });
  16080. thread t = thread([&] { svr.listen(HOST, PORT); });
  16081. auto se = detail::scope_exit([&] {
  16082. svr.stop();
  16083. t.join();
  16084. ASSERT_FALSE(svr.is_running());
  16085. ASSERT_TRUE(handled);
  16086. });
  16087. svr.wait_until_ready();
  16088. auto boundary = std::string("cpp-httplib-multipart-data");
  16089. std::string content = "--" + boundary +
  16090. "\r\n"
  16091. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16092. "\r\n"
  16093. "text1\r\n"
  16094. "--" +
  16095. boundary + "--\r\n";
  16096. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16097. "Host: localhost\r\n"
  16098. "Content-Type: multipart/form-data;boundary=" +
  16099. boundary +
  16100. "\r\n"
  16101. "Content-Length: " +
  16102. std::to_string(content.size()) +
  16103. "\r\n"
  16104. "Dummy-Header: ";
  16105. std::string header_suffix = "\r\n"
  16106. "\r\n";
  16107. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16108. size_t header_dummy_size =
  16109. read_buff_size -
  16110. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16111. auto header_dummy = std::string(header_dummy_size, '@');
  16112. auto req = header_prefix + header_dummy + header_suffix + content;
  16113. std::string response;
  16114. ASSERT_TRUE(send_request(1, req, &response));
  16115. ASSERT_EQ("200", response.substr(9, 3));
  16116. }
  16117. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16118. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16119. // (not chunked Transfer-Encoding) after the streaming refactor.
  16120. auto handled = false;
  16121. Server svr;
  16122. svr.Post("/upload", [&](const Request &req, Response &res) {
  16123. auto cl_it = req.headers.find("Content-Length");
  16124. EXPECT_TRUE(cl_it != req.headers.end());
  16125. auto te_it = req.headers.find("Transfer-Encoding");
  16126. EXPECT_TRUE(te_it == req.headers.end());
  16127. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16128. res.set_content("ok", "text/plain");
  16129. handled = true;
  16130. });
  16131. auto port = svr.bind_to_any_port(HOST);
  16132. auto t = thread([&] { svr.listen_after_bind(); });
  16133. auto se = detail::scope_exit([&] {
  16134. svr.stop();
  16135. t.join();
  16136. ASSERT_FALSE(svr.is_running());
  16137. ASSERT_TRUE(handled);
  16138. });
  16139. svr.wait_until_ready();
  16140. UploadFormDataItems items = {
  16141. {"field1", "hello", "", "text/plain"},
  16142. {"file1", "world", "test.txt", "application/octet-stream"},
  16143. };
  16144. Client cli(HOST, port);
  16145. auto res = cli.Post("/upload", {}, items);
  16146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16147. EXPECT_EQ(StatusCode::OK_200, res->status);
  16148. }
  16149. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16150. // Verify that make_multipart_content_provider coalesces many small segments
  16151. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16152. constexpr size_t kItemCount = 1000;
  16153. UploadFormDataItems items;
  16154. items.reserve(kItemCount);
  16155. for (size_t i = 0; i < kItemCount; i++) {
  16156. items.push_back(
  16157. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16158. }
  16159. const std::string boundary = "----test-boundary";
  16160. auto content_length = detail::get_multipart_content_length(items, boundary);
  16161. auto provider = detail::make_multipart_content_provider(items, boundary);
  16162. // Drive the provider the same way write_content_with_progress does
  16163. size_t write_count = 0;
  16164. size_t total_bytes = 0;
  16165. DataSink sink;
  16166. size_t offset = 0;
  16167. sink.write = [&](const char *d, size_t l) -> bool {
  16168. (void)d;
  16169. write_count++;
  16170. total_bytes += l;
  16171. offset += l;
  16172. return true;
  16173. };
  16174. sink.is_writable = []() -> bool { return true; };
  16175. while (offset < content_length) {
  16176. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16177. }
  16178. EXPECT_EQ(content_length, total_bytes);
  16179. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16180. // With buffering into 64KB blocks, write_count should be much smaller.
  16181. auto segment_count = 3 * kItemCount + 1;
  16182. EXPECT_LT(write_count, segment_count / 10);
  16183. }
  16184. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16185. // Integration test: send many UploadFormDataItems and verify the server
  16186. // receives all of them correctly (#2410).
  16187. constexpr size_t kItemCount = 500;
  16188. auto handled = false;
  16189. Server svr;
  16190. svr.Post("/upload", [&](const Request &req, Response &res) {
  16191. EXPECT_EQ(kItemCount, req.form.fields.size());
  16192. for (size_t i = 0; i < kItemCount; i++) {
  16193. auto key = "field" + std::to_string(i);
  16194. auto val = "value" + std::to_string(i);
  16195. auto it = req.form.fields.find(key);
  16196. if (it != req.form.fields.end()) {
  16197. EXPECT_EQ(val, it->second.content);
  16198. } else {
  16199. ADD_FAILURE() << "Missing field: " << key;
  16200. }
  16201. }
  16202. res.set_content("ok", "text/plain");
  16203. handled = true;
  16204. });
  16205. auto port = svr.bind_to_any_port(HOST);
  16206. auto t = thread([&] { svr.listen_after_bind(); });
  16207. auto se = detail::scope_exit([&] {
  16208. svr.stop();
  16209. t.join();
  16210. ASSERT_FALSE(svr.is_running());
  16211. ASSERT_TRUE(handled);
  16212. });
  16213. svr.wait_until_ready();
  16214. UploadFormDataItems items;
  16215. items.reserve(kItemCount);
  16216. for (size_t i = 0; i < kItemCount; i++) {
  16217. items.push_back(
  16218. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16219. }
  16220. Client cli(HOST, port);
  16221. auto res = cli.Post("/upload", items);
  16222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16223. EXPECT_EQ(StatusCode::OK_200, res->status);
  16224. }
  16225. TEST(MultipartFormDataTest, MakeFileProvider) {
  16226. // Verify make_file_provider sends a file's contents correctly.
  16227. const std::string file_content(4096, 'Z');
  16228. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16229. {
  16230. std::ofstream ofs(tmp_path, std::ios::binary);
  16231. ofs.write(file_content.data(),
  16232. static_cast<std::streamsize>(file_content.size()));
  16233. }
  16234. auto handled = false;
  16235. Server svr;
  16236. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16237. const ContentReader &content_reader) {
  16238. ASSERT_TRUE(req.is_multipart_form_data());
  16239. std::vector<FormData> items;
  16240. content_reader(
  16241. [&](const FormData &file) {
  16242. items.push_back(file);
  16243. return true;
  16244. },
  16245. [&](const char *data, size_t data_length) {
  16246. items.back().content.append(data, data_length);
  16247. return true;
  16248. });
  16249. ASSERT_EQ(1u, items.size());
  16250. EXPECT_EQ("myfile", items[0].name);
  16251. EXPECT_EQ("data.bin", items[0].filename);
  16252. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16253. EXPECT_EQ(file_content, items[0].content);
  16254. handled = true;
  16255. });
  16256. auto port = svr.bind_to_any_port(HOST);
  16257. auto t = thread([&] { svr.listen_after_bind(); });
  16258. auto se = detail::scope_exit([&] {
  16259. svr.stop();
  16260. t.join();
  16261. ASSERT_FALSE(svr.is_running());
  16262. ASSERT_TRUE(handled);
  16263. std::remove(tmp_path.c_str());
  16264. });
  16265. svr.wait_until_ready();
  16266. FormDataProviderItems providers;
  16267. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16268. "application/octet-stream"));
  16269. Client cli(HOST, port);
  16270. auto res = cli.Post("/upload", {}, {}, providers);
  16271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16272. EXPECT_EQ(StatusCode::OK_200, res->status);
  16273. }
  16274. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16275. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16276. // (100) headers is rejected with a 400 Bad Request response.
  16277. Server svr;
  16278. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16279. res.set_content("ok", "text/plain");
  16280. });
  16281. thread t = thread([&] { svr.listen(HOST, PORT); });
  16282. auto se = detail::scope_exit([&] {
  16283. svr.stop();
  16284. t.join();
  16285. ASSERT_FALSE(svr.is_running());
  16286. });
  16287. svr.wait_until_ready();
  16288. // Build a multipart part with 101 custom headers (exceeding
  16289. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16290. std::stringstream body;
  16291. body << "--simpleboundary\r\n"
  16292. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16293. for (int i = 0; i < 101; i++) {
  16294. body << "X-Custom-Header-" << i << ": value\r\n";
  16295. }
  16296. body << "\r\n"
  16297. << "value1\r\n"
  16298. << "--simpleboundary--\r\n";
  16299. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16300. Client cli(HOST, PORT);
  16301. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16303. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16304. }
  16305. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16306. // A body that never contains the declared boundary must not be accumulated
  16307. // while the parser waits for it. Buffering it would also make every read
  16308. // rescan everything seen so far, which is quadratic in the body size.
  16309. Server svr;
  16310. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16311. res.set_content("ok", "text/plain");
  16312. });
  16313. auto port = svr.bind_to_any_port(HOST);
  16314. thread t = thread([&] { svr.listen_after_bind(); });
  16315. auto se = detail::scope_exit([&] {
  16316. svr.stop();
  16317. t.join();
  16318. ASSERT_FALSE(svr.is_running());
  16319. });
  16320. svr.wait_until_ready();
  16321. Client cli(HOST, port);
  16322. cli.set_read_timeout(60, 0);
  16323. cli.set_write_timeout(60, 0);
  16324. // '-' is the worst case: it matches the first character of the boundary, so
  16325. // every position has to be checked against it.
  16326. auto post_dashes = [&](size_t size) {
  16327. const std::string body(size, '-');
  16328. auto start = std::chrono::steady_clock::now();
  16329. auto res =
  16330. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16331. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16332. std::chrono::steady_clock::now() - start)
  16333. .count();
  16334. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16335. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16336. return ms;
  16337. };
  16338. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16339. // Windows.
  16340. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16341. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16342. // Comparing the two sizes rather than checking an absolute duration keeps
  16343. // this meaningful across build types and CI load, both of which move the
  16344. // absolute numbers by more than an order of magnitude. Four times the bytes
  16345. // costs about four times the time when parsing is linear, and about sixteen
  16346. // times when the body is buffered and rescanned.
  16347. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16348. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16349. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16350. << "ms, which suggests the body is being buffered and rescanned";
  16351. }
  16352. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16353. // A boundary can only be followed by CRLF or by "--", so anything else is
  16354. // malformed no matter what comes next. The parser must say so right away
  16355. // instead of buffering the rest of the declared body.
  16356. Server svr;
  16357. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16358. res.set_content("ok", "text/plain");
  16359. });
  16360. auto port = svr.bind_to_any_port(HOST);
  16361. thread t = thread([&] { svr.listen_after_bind(); });
  16362. auto se = detail::scope_exit([&] {
  16363. svr.stop();
  16364. t.join();
  16365. ASSERT_FALSE(svr.is_running());
  16366. });
  16367. svr.wait_until_ready();
  16368. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16369. // buffers instead of failing would still be waiting for the remaining bytes.
  16370. const std::string body = "--zzzz\r\n"
  16371. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16372. "\r\n"
  16373. "text1"
  16374. "\r\n--zzzzXX";
  16375. const std::string req = "POST /post HTTP/1.1\r\n"
  16376. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16377. "Content-Length: 1048576\r\n"
  16378. "\r\n" +
  16379. body;
  16380. std::string response;
  16381. ASSERT_TRUE(send_request(3, req, &response, port));
  16382. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16383. EXPECT_EQ("400", response.substr(9, 3));
  16384. }
  16385. // Posts a multipart body split into two writes, so that the server sees the
  16386. // split at whatever offset the caller chose, and expects the single "text1"
  16387. // field to come through.
  16388. static void expect_split_multipart_ok(const std::string &body1,
  16389. const std::string &body2) {
  16390. auto handled = false;
  16391. Server svr;
  16392. svr.Post("/post", [&](const Request &req, Response &) {
  16393. EXPECT_EQ(1u, req.form.fields.size());
  16394. EXPECT_EQ("text1", req.form.get_field("text1"));
  16395. handled = true;
  16396. });
  16397. auto port = svr.bind_to_any_port(HOST);
  16398. thread t = thread([&] { svr.listen_after_bind(); });
  16399. auto se = detail::scope_exit([&] {
  16400. svr.stop();
  16401. t.join();
  16402. ASSERT_FALSE(svr.is_running());
  16403. ASSERT_TRUE(handled);
  16404. });
  16405. svr.wait_until_ready();
  16406. // "Connection: close" makes the server close once it has answered, so the
  16407. // response drain ends immediately instead of idling until the read timeout.
  16408. const std::string head =
  16409. "POST /post HTTP/1.1\r\n"
  16410. "Host: localhost\r\n"
  16411. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16412. "Connection: close\r\n"
  16413. "Content-Length: " +
  16414. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16415. std::string response;
  16416. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16417. ASSERT_GE(response.size(), 12u) << "no response";
  16418. EXPECT_EQ("200", response.substr(9, 3));
  16419. }
  16420. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16421. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16422. // ignored, including when it does not arrive in the same read as the
  16423. // close-delimiter itself.
  16424. expect_split_multipart_ok("--zzzz\r\n"
  16425. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16426. "\r\n"
  16427. "text1"
  16428. "\r\n--zzzz--",
  16429. "\r\nthis epilogue must be ignored\r\n");
  16430. }
  16431. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16432. // The initial boundary may be preceded by a preamble of any length and may
  16433. // straddle a read boundary. Discarding data while waiting for it must not
  16434. // throw away a partial boundary sitting at the end of the buffer.
  16435. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16436. "zz\r\n"
  16437. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16438. "\r\n"
  16439. "text1"
  16440. "\r\n--zzzz--\r\n");
  16441. }
  16442. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16443. // The received boundary was only checked for being non-empty, so it could be
  16444. // as long as a header is allowed to be. The parser scans the body for
  16445. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16446. // costs a nearly full comparison at nearly every position, making the
  16447. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16448. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16449. Server svr;
  16450. svr.Post("/post", [](const Request &req, Response &res) {
  16451. EXPECT_EQ(1u, req.form.fields.size());
  16452. EXPECT_EQ("text1", req.form.get_field("text1"));
  16453. res.set_content("ok", "text/plain");
  16454. });
  16455. auto port = svr.bind_to_any_port(HOST);
  16456. thread t = thread([&] { svr.listen_after_bind(); });
  16457. auto se = detail::scope_exit([&] {
  16458. svr.stop();
  16459. t.join();
  16460. ASSERT_FALSE(svr.is_running());
  16461. });
  16462. svr.wait_until_ready();
  16463. Client cli(HOST, port);
  16464. auto post_with_boundary_of_length = [&](size_t len) {
  16465. const std::string boundary(len, 'a');
  16466. const std::string body =
  16467. "--" + boundary +
  16468. "\r\n"
  16469. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16470. "\r\n"
  16471. "text1"
  16472. "\r\n--" +
  16473. boundary + "--\r\n";
  16474. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16475. };
  16476. auto res = post_with_boundary_of_length(70);
  16477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16478. EXPECT_EQ(StatusCode::OK_200, res->status);
  16479. res = post_with_boundary_of_length(71);
  16480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16481. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16482. }
  16483. TEST(MakeFileBodyTest, Basic) {
  16484. const std::string file_content(4096, 'Z');
  16485. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16486. {
  16487. std::ofstream ofs(tmp_path, std::ios::binary);
  16488. ofs.write(file_content.data(),
  16489. static_cast<std::streamsize>(file_content.size()));
  16490. }
  16491. auto handled = false;
  16492. Server svr;
  16493. svr.Post("/upload", [&](const Request &req, Response &res) {
  16494. EXPECT_EQ(file_content, req.body);
  16495. handled = true;
  16496. res.status = StatusCode::OK_200;
  16497. });
  16498. auto port = svr.bind_to_any_port(HOST);
  16499. auto t = thread([&] { svr.listen_after_bind(); });
  16500. auto se = detail::scope_exit([&] {
  16501. svr.stop();
  16502. t.join();
  16503. ASSERT_FALSE(svr.is_running());
  16504. ASSERT_TRUE(handled);
  16505. std::remove(tmp_path.c_str());
  16506. });
  16507. svr.wait_until_ready();
  16508. auto fb = make_file_body(tmp_path);
  16509. ASSERT_GT(fb.first, 0u);
  16510. Client cli(HOST, port);
  16511. auto res =
  16512. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16514. EXPECT_EQ(StatusCode::OK_200, res->status);
  16515. }
  16516. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16517. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16518. {
  16519. std::ofstream ofs(path, std::ios::binary);
  16520. const std::string content(100, 'A');
  16521. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16522. }
  16523. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16524. auto body = make_file_body(path);
  16525. ASSERT_EQ(100u, body.first);
  16526. ASSERT_TRUE(static_cast<bool>(body.second));
  16527. // Rewritten shorter after its length was measured - and, on a server, after
  16528. // that length has already gone out as Content-Length.
  16529. {
  16530. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16531. const std::string content(10, 'A');
  16532. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16533. }
  16534. std::string written;
  16535. DataSink sink;
  16536. sink.write = [&](const char *d, size_t l) {
  16537. written.append(d, l);
  16538. return true;
  16539. };
  16540. // The provider has to report failure. write_content_with_progress() advances
  16541. // its offset only by what was written, so a provider that returns true
  16542. // without completing the length it promised is called again straight away,
  16543. // and again.
  16544. EXPECT_FALSE(body.second(0, body.first, sink));
  16545. EXPECT_EQ(std::string(10, 'A'), written);
  16546. }
  16547. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16548. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16549. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16550. {
  16551. std::ofstream ofs(path, std::ios::binary);
  16552. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16553. }
  16554. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16555. auto body = make_file_body(path);
  16556. ASSERT_EQ(content.size(), body.first);
  16557. ASSERT_TRUE(static_cast<bool>(body.second));
  16558. std::string written;
  16559. DataSink sink;
  16560. sink.write = [&](const char *d, size_t l) {
  16561. written.append(d, l);
  16562. return true;
  16563. };
  16564. EXPECT_TRUE(body.second(0, body.first, sink));
  16565. EXPECT_EQ(content, written);
  16566. }
  16567. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16568. static constexpr unsigned int number_of_tasks{1000000};
  16569. std::atomic_uint count{0};
  16570. std::unique_ptr<TaskQueue> task_queue{
  16571. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16572. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16573. auto queued = task_queue->enqueue(
  16574. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16575. EXPECT_TRUE(queued);
  16576. }
  16577. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16578. task_queue->shutdown();
  16579. #else
  16580. EXPECT_NO_THROW(task_queue->shutdown());
  16581. #endif
  16582. EXPECT_EQ(number_of_tasks, count.load());
  16583. }
  16584. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16585. static constexpr unsigned int number_of_tasks{1000000};
  16586. static constexpr unsigned int qlimit{2};
  16587. unsigned int queued_count{0};
  16588. std::atomic_uint count{0};
  16589. std::unique_ptr<TaskQueue> task_queue{
  16590. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16591. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16592. if (task_queue->enqueue(
  16593. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16594. queued_count++;
  16595. }
  16596. }
  16597. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16598. task_queue->shutdown();
  16599. #else
  16600. EXPECT_NO_THROW(task_queue->shutdown());
  16601. #endif
  16602. EXPECT_EQ(queued_count, count.load());
  16603. EXPECT_TRUE(queued_count <= number_of_tasks);
  16604. EXPECT_TRUE(queued_count >= qlimit);
  16605. }
  16606. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16607. // Use a short idle timeout so a dynamic thread spawns, times out and
  16608. // exits during the test, and the pool keeps working afterwards.
  16609. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16610. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16611. /*idle_timeout_sec=*/1}};
  16612. std::atomic_uint count{0};
  16613. std::condition_variable cv;
  16614. std::mutex mtx;
  16615. bool release = false;
  16616. // Block the base thread so the second task spawns a dynamic thread.
  16617. EXPECT_TRUE(task_queue->enqueue([&] {
  16618. std::unique_lock<std::mutex> lock(mtx);
  16619. while (!release) {
  16620. cv.wait(lock);
  16621. }
  16622. count++;
  16623. }));
  16624. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16625. // Let the dynamic thread finish its task and exceed the idle timeout.
  16626. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16627. {
  16628. std::unique_lock<std::mutex> lock(mtx);
  16629. release = true;
  16630. }
  16631. cv.notify_all();
  16632. // The pool must still accept and run tasks after the dynamic thread exited.
  16633. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16634. task_queue->shutdown();
  16635. EXPECT_EQ(3u, count.load());
  16636. }
  16637. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16638. static constexpr size_t number_of_tasks{32};
  16639. std::unique_ptr<TaskQueue> task_queue{
  16640. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16641. // Let the base threads go idle so the burst below finds them waiting.
  16642. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16643. std::mutex mtx;
  16644. std::condition_variable cv;
  16645. size_t running = 0;
  16646. bool release = false;
  16647. for (size_t i = 0; i < number_of_tasks; i++) {
  16648. EXPECT_TRUE(task_queue->enqueue([&] {
  16649. std::unique_lock<std::mutex> lock(mtx);
  16650. running++;
  16651. cv.notify_all();
  16652. cv.wait(lock, [&] { return release; });
  16653. }));
  16654. }
  16655. {
  16656. std::unique_lock<std::mutex> lock(mtx);
  16657. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16658. [&] { return running == number_of_tasks; }));
  16659. release = true;
  16660. }
  16661. cv.notify_all();
  16662. task_queue->shutdown();
  16663. }
  16664. TEST(TaskQueueTest, MaxQueuedRequests) {
  16665. static constexpr unsigned int qlimit{3};
  16666. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16667. std::condition_variable sem_cv;
  16668. std::mutex sem_mtx;
  16669. int credits = 0;
  16670. bool queued;
  16671. /* Fill up the queue with tasks that will block until we give them credits to
  16672. * complete. */
  16673. for (unsigned int n = 0; n <= qlimit;) {
  16674. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16675. std::unique_lock<std::mutex> lock(sem_mtx);
  16676. while (credits <= 0) {
  16677. sem_cv.wait(lock);
  16678. }
  16679. /* Consume the credit and signal the test code if they are all gone. */
  16680. if (--credits == 0) { sem_cv.notify_one(); }
  16681. });
  16682. if (n < qlimit) {
  16683. /* The first qlimit enqueues must succeed. */
  16684. EXPECT_TRUE(queued);
  16685. } else {
  16686. /* The last one will succeed only when the worker thread
  16687. * starts and dequeues the first blocking task. Although
  16688. * not necessary for the correctness of this test, we sleep for
  16689. * a short while to avoid busy waiting. */
  16690. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16691. }
  16692. if (queued) { n++; }
  16693. }
  16694. /* Further enqueues must fail since the queue is full. */
  16695. for (auto i = 0; i < 4; i++) {
  16696. queued = task_queue->enqueue([] {});
  16697. EXPECT_FALSE(queued);
  16698. }
  16699. /* Give the credits to allow the previous tasks to complete. */
  16700. {
  16701. std::unique_lock<std::mutex> lock(sem_mtx);
  16702. credits += qlimit + 1;
  16703. }
  16704. sem_cv.notify_all();
  16705. /* Wait for all the credits to be consumed. */
  16706. {
  16707. std::unique_lock<std::mutex> lock(sem_mtx);
  16708. while (credits > 0) {
  16709. sem_cv.wait(lock);
  16710. }
  16711. }
  16712. /* Check that we are able again to enqueue at least qlimit tasks. */
  16713. for (unsigned int i = 0; i < qlimit; i++) {
  16714. queued = task_queue->enqueue([] {});
  16715. EXPECT_TRUE(queued);
  16716. }
  16717. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16718. task_queue->shutdown();
  16719. #else
  16720. EXPECT_NO_THROW(task_queue->shutdown());
  16721. #endif
  16722. }
  16723. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16724. Server svr;
  16725. std::string method;
  16726. std::string body;
  16727. auto has_content_length = false;
  16728. auto has_transfer_encoding = false;
  16729. std::atomic<int> bad_requests{0};
  16730. // Leftover body bytes get parsed as a malformed request and answered with
  16731. // 400
  16732. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16733. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16734. });
  16735. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16736. res.set_redirect("/down", StatusCode::SeeOther_303);
  16737. });
  16738. svr.Get("/down", [&](const Request &req, Response &res) {
  16739. method = req.method;
  16740. body = req.body;
  16741. has_content_length = req.has_header("Content-Length");
  16742. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16743. res.set_content("ok", "text/plain");
  16744. });
  16745. auto port = svr.bind_to_any_port(HOST);
  16746. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16747. auto se = detail::scope_exit([&] {
  16748. svr.stop();
  16749. thread.join();
  16750. ASSERT_FALSE(svr.is_running());
  16751. });
  16752. svr.wait_until_ready();
  16753. const std::string payload = "SECRET-BODY";
  16754. auto check = [&](Client &cli, const Result &res) {
  16755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16756. EXPECT_EQ(StatusCode::OK_200, res->status);
  16757. EXPECT_EQ("ok", res->body);
  16758. EXPECT_EQ("GET", method);
  16759. EXPECT_TRUE(body.empty());
  16760. EXPECT_FALSE(has_content_length);
  16761. EXPECT_FALSE(has_transfer_encoding);
  16762. // Nothing of the original body may be left on the connection
  16763. auto res2 = cli.Get("/down");
  16764. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16765. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16766. EXPECT_EQ("ok", res2->body);
  16767. EXPECT_EQ(0, bad_requests);
  16768. };
  16769. // With content length
  16770. {
  16771. Client cli(HOST, port);
  16772. cli.set_keep_alive(true);
  16773. cli.set_follow_location(true);
  16774. auto res = cli.Post(
  16775. "/up", payload.size(),
  16776. [&](size_t offset, size_t length, DataSink &sink) {
  16777. return sink.write(payload.data() + offset, length);
  16778. },
  16779. "text/plain");
  16780. check(cli, res);
  16781. }
  16782. // Without content length (chunked)
  16783. {
  16784. Client cli(HOST, port);
  16785. cli.set_keep_alive(true);
  16786. cli.set_follow_location(true);
  16787. auto res = cli.Post(
  16788. "/up",
  16789. [&](size_t /*offset*/, DataSink &sink) {
  16790. sink.write(payload.data(), payload.size());
  16791. sink.done();
  16792. return true;
  16793. },
  16794. "text/plain");
  16795. check(cli, res);
  16796. }
  16797. }
  16798. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16799. Server svr;
  16800. std::string target;
  16801. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16802. // Echo the still-encoded name back in the Location
  16803. const std::string prefix = "/start/";
  16804. res.status = StatusCode::Found_302;
  16805. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16806. });
  16807. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16808. target = req.target;
  16809. res.set_content("ok", "text/plain");
  16810. });
  16811. auto port = svr.bind_to_any_port(HOST);
  16812. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16813. auto se = detail::scope_exit([&] {
  16814. svr.stop();
  16815. thread.join();
  16816. ASSERT_FALSE(svr.is_running());
  16817. });
  16818. svr.wait_until_ready();
  16819. // Decoding the Location path would turn the first four into a path
  16820. // separator, a query delimiter, a fragment delimiter and a different
  16821. // percent-encoded octet. The rest must keep reaching the server as they are.
  16822. const std::vector<std::string> names = {
  16823. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16824. };
  16825. for (auto path_encode : {true, false}) {
  16826. Client cli(HOST, port);
  16827. cli.set_follow_location(true);
  16828. cli.set_path_encode(path_encode);
  16829. for (const auto &name : names) {
  16830. target.clear();
  16831. auto res = cli.Get("/start/" + name);
  16832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16833. EXPECT_EQ(StatusCode::OK_200, res->status);
  16834. EXPECT_EQ("/dest/" + name, target);
  16835. }
  16836. }
  16837. }
  16838. TEST(RedirectTest, NotModifiedIsReturned) {
  16839. Server svr;
  16840. svr.Get("/cached", [](const Request &, Response &res) {
  16841. res.status = StatusCode::NotModified_304;
  16842. });
  16843. auto port = svr.bind_to_any_port(HOST);
  16844. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16845. auto se = detail::scope_exit([&] {
  16846. svr.stop();
  16847. thread.join();
  16848. ASSERT_FALSE(svr.is_running());
  16849. });
  16850. svr.wait_until_ready();
  16851. Client cli(HOST, port);
  16852. cli.set_follow_location(true);
  16853. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16855. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16856. }
  16857. TEST(RedirectTest, NoLocationIsReturned) {
  16858. Server svr;
  16859. svr.Get("/no-location", [](const Request &, Response &res) {
  16860. res.status = StatusCode::Found_302;
  16861. res.set_content("no location", "text/plain");
  16862. });
  16863. auto port = svr.bind_to_any_port(HOST);
  16864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16865. auto se = detail::scope_exit([&] {
  16866. svr.stop();
  16867. thread.join();
  16868. ASSERT_FALSE(svr.is_running());
  16869. });
  16870. svr.wait_until_ready();
  16871. Client cli(HOST, port);
  16872. cli.set_follow_location(true);
  16873. auto res = cli.Get("/no-location");
  16874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16875. EXPECT_EQ(StatusCode::Found_302, res->status);
  16876. EXPECT_EQ("no location", res->body);
  16877. // The callbacks see the body of the response that is returned
  16878. auto handler_called = false;
  16879. auto progress_called = false;
  16880. std::string body;
  16881. auto res2 = cli.Get(
  16882. "/no-location",
  16883. [&](const Response &) {
  16884. handler_called = true;
  16885. return true;
  16886. },
  16887. [&](const char *data, size_t data_length) {
  16888. body.append(data, data_length);
  16889. return true;
  16890. },
  16891. [&](size_t, size_t) {
  16892. progress_called = true;
  16893. return true;
  16894. });
  16895. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16896. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16897. EXPECT_TRUE(handler_called);
  16898. EXPECT_TRUE(progress_called);
  16899. EXPECT_EQ("no location", body);
  16900. }
  16901. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16902. Server svr;
  16903. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16904. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16905. });
  16906. svr.Get("/hello", [](const Request &req, Response &res) {
  16907. res.set_content(req.get_param_value("key"), "text/plain");
  16908. });
  16909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16910. auto se = detail::scope_exit([&] {
  16911. svr.stop();
  16912. thread.join();
  16913. ASSERT_FALSE(svr.is_running());
  16914. });
  16915. svr.wait_until_ready();
  16916. {
  16917. Client cli(HOST, PORT);
  16918. cli.set_follow_location(true);
  16919. auto res = cli.Get("/");
  16920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16921. EXPECT_EQ(StatusCode::OK_200, res->status);
  16922. EXPECT_EQ("val&key2=val2", res->body);
  16923. }
  16924. }
  16925. #endif
  16926. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16927. Server svr;
  16928. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16929. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16930. });
  16931. svr.Get("/hello", [](const Request &req, Response &res) {
  16932. res.set_content(req.get_param_value("key"), "text/plain");
  16933. });
  16934. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16935. auto se = detail::scope_exit([&] {
  16936. svr.stop();
  16937. thread.join();
  16938. ASSERT_FALSE(svr.is_running());
  16939. });
  16940. svr.wait_until_ready();
  16941. {
  16942. Client cli(HOST, PORT);
  16943. cli.set_follow_location(true);
  16944. auto res = cli.Get("/");
  16945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16946. EXPECT_EQ(StatusCode::OK_200, res->status);
  16947. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16948. }
  16949. }
  16950. TEST(RedirectTest, RedirectWithPlusInPath) {
  16951. Server svr;
  16952. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16953. res.set_redirect("/a+b");
  16954. });
  16955. // Route pattern uses regex; escape + as \\+
  16956. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16957. res.set_content(req.path, "text/plain");
  16958. });
  16959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16960. auto se = detail::scope_exit([&] {
  16961. svr.stop();
  16962. thread.join();
  16963. ASSERT_FALSE(svr.is_running());
  16964. });
  16965. svr.wait_until_ready();
  16966. {
  16967. Client cli(HOST, PORT);
  16968. cli.set_follow_location(true);
  16969. auto res = cli.Get("/");
  16970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16971. EXPECT_EQ(StatusCode::OK_200, res->status);
  16972. EXPECT_EQ("/a+b", res->body);
  16973. }
  16974. }
  16975. TEST(RedirectTest, ResolveRelativeLocation) {
  16976. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16977. const std::vector<std::pair<std::string, std::string>> cases = {
  16978. {"g", "/b/c/g"},
  16979. {"./g", "/b/c/g"},
  16980. {"g/", "/b/c/g/"},
  16981. {"?y", "/b/c/d;p?y"},
  16982. {"g?y", "/b/c/g?y"},
  16983. {"#s", "/b/c/d;p?q#s"},
  16984. {"g#s", "/b/c/g#s"},
  16985. {"g?y#s", "/b/c/g?y#s"},
  16986. {";x", "/b/c/;x"},
  16987. {"g;x", "/b/c/g;x"},
  16988. {".", "/b/c/"},
  16989. {"./", "/b/c/"},
  16990. {"..", "/b/"},
  16991. {"../", "/b/"},
  16992. {"../g", "/b/g"},
  16993. {"../..", "/"},
  16994. {"../../", "/"},
  16995. {"../../g", "/g"},
  16996. {"../../../g", "/g"},
  16997. {"g.", "/b/c/g."},
  16998. {".g", "/b/c/.g"},
  16999. {"g..", "/b/c/g.."},
  17000. {"..g", "/b/c/..g"},
  17001. {"./../g", "/b/g"},
  17002. {"./g/.", "/b/c/g/"},
  17003. {"g/./h", "/b/c/g/h"},
  17004. {"g/../h", "/b/c/h"},
  17005. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17006. {"g;x=1/../y", "/b/c/y"},
  17007. {"g?y/./x", "/b/c/g?y/./x"},
  17008. {"g#s/../x", "/b/c/g#s/../x"},
  17009. // Not relative-path references, so left for parse_url.
  17010. {"/g", "/g"},
  17011. {"//g", "//g"},
  17012. {"http://g/x", "http://g/x"},
  17013. {"g:h", "g:h"},
  17014. };
  17015. for (const auto &c : cases) {
  17016. EXPECT_EQ(c.second,
  17017. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17018. << c.first;
  17019. }
  17020. }
  17021. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17022. Server svr;
  17023. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17024. res.set_redirect(req.get_param_value("to"));
  17025. });
  17026. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17027. res.set_content(req.target, "text/plain");
  17028. });
  17029. svr.Get("/other", [](const Request &req, Response &res) {
  17030. res.set_content(req.target, "text/plain");
  17031. });
  17032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17033. auto se = detail::scope_exit([&] {
  17034. svr.stop();
  17035. thread.join();
  17036. ASSERT_FALSE(svr.is_running());
  17037. });
  17038. svr.wait_until_ready();
  17039. const std::vector<std::pair<std::string, std::string>> cases = {
  17040. {"next", "/dir/next"},
  17041. {"./next?x=1", "/dir/next?x=1"},
  17042. {"../other", "/other"},
  17043. };
  17044. for (const auto &c : cases) {
  17045. Client cli(HOST, PORT);
  17046. cli.set_follow_location(true);
  17047. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17048. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17049. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17050. EXPECT_EQ(c.second, res->body) << c.first;
  17051. }
  17052. }
  17053. #ifdef CPPHTTPLIB_SSL_ENABLED
  17054. TEST(RedirectTest, Issue2185_Online) {
  17055. SSLClient client("github.com");
  17056. client.set_follow_location(true);
  17057. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17058. "Coollab-Windows.zip");
  17059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17060. EXPECT_EQ(StatusCode::OK_200, res->status);
  17061. EXPECT_EQ(9920427U, res->body.size());
  17062. }
  17063. #endif
  17064. TEST(VulnerabilityTest, CRLFInjection) {
  17065. Server svr;
  17066. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17067. res.set_content("Hello 1", "text/plain");
  17068. });
  17069. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17070. res.set_content("Hello 2", "text/plain");
  17071. });
  17072. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17073. res.set_content("Hello 3", "text/plain");
  17074. });
  17075. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17076. res.set_content("Hello 4", "text/plain");
  17077. });
  17078. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17079. for (const auto &x : req.headers) {
  17080. auto key = x.first;
  17081. EXPECT_STRNE("evil", key.c_str());
  17082. }
  17083. });
  17084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17085. auto se = detail::scope_exit([&] {
  17086. svr.stop();
  17087. thread.join();
  17088. ASSERT_FALSE(svr.is_running());
  17089. });
  17090. svr.wait_until_ready();
  17091. {
  17092. Client cli(HOST, PORT);
  17093. cli.Post("/test1", "A=B",
  17094. "application/x-www-form-urlencoded\r\nevil: hello1");
  17095. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17096. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17097. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17098. }
  17099. }
  17100. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17101. auto server_thread = std::thread([] {
  17102. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17103. default_socket_options(srv);
  17104. sockaddr_in addr{};
  17105. addr.sin_family = AF_INET;
  17106. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17108. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17109. ::listen(srv, 1);
  17110. sockaddr_in cli_addr{};
  17111. socklen_t cli_len = sizeof(cli_addr);
  17112. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17113. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17114. std::string buf_all;
  17115. char buf[2048];
  17116. ssize_t n;
  17117. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17118. buf_all.append(buf, static_cast<size_t>(n));
  17119. size_t pos;
  17120. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17121. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17122. auto e = request_block.find("\r\n");
  17123. if (e != std::string::npos) {
  17124. auto request_line = request_block.substr(0, e);
  17125. std::string msg =
  17126. "CRLF injection detected in request line: '" + request_line + "'";
  17127. EXPECT_FALSE(true) << msg;
  17128. }
  17129. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17130. ::send(cli,
  17131. #ifdef _WIN32
  17132. static_cast<const char *>(resp.c_str()),
  17133. static_cast<int>(resp.size()),
  17134. #else
  17135. resp.c_str(), resp.size(),
  17136. #endif
  17137. 0);
  17138. buf_all.erase(0, pos + 4);
  17139. }
  17140. }
  17141. detail::close_socket(cli);
  17142. detail::close_socket(srv);
  17143. });
  17144. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17145. auto cli = Client("127.0.0.1", PORT + 1);
  17146. auto headers = Headers{
  17147. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17148. {"Connection", "keep-alive"}};
  17149. auto res = cli.Get("/hi", headers);
  17150. EXPECT_FALSE(res);
  17151. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17152. server_thread.join();
  17153. }
  17154. // A request rejected before any byte reaches the socket must fail right away
  17155. // instead of waiting for a response the server will never send.
  17156. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17157. // The kernel completes the TCP handshake from the listen backlog, so the
  17158. // client connects, but nothing ever reads, responds or closes.
  17159. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17160. default_socket_options(srv);
  17161. sockaddr_in addr{};
  17162. addr.sin_family = AF_INET;
  17163. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17164. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17165. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17166. ASSERT_EQ(0, ::listen(srv, 8));
  17167. auto cli = Client("127.0.0.1", PORT + 1);
  17168. cli.set_read_timeout(10, 0);
  17169. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17170. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17171. std::chrono::steady_clock::now() - start)
  17172. .count();
  17173. };
  17174. {
  17175. Request req;
  17176. req.method = "GE T";
  17177. req.path = "/";
  17178. auto start = std::chrono::steady_clock::now();
  17179. auto res = cli.send(req);
  17180. EXPECT_FALSE(res);
  17181. EXPECT_EQ(Error::Write, res.error());
  17182. EXPECT_LT(elapsed_ms(start), 1000);
  17183. }
  17184. {
  17185. auto start = std::chrono::steady_clock::now();
  17186. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17187. EXPECT_FALSE(res);
  17188. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17189. EXPECT_LT(elapsed_ms(start), 1000);
  17190. }
  17191. EXPECT_FALSE(cli.is_socket_open());
  17192. detail::close_socket(srv);
  17193. }
  17194. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17195. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17196. default_socket_options(srv);
  17197. sockaddr_in addr{};
  17198. addr.sin_family = AF_INET;
  17199. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17200. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17201. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17202. ASSERT_EQ(0, ::listen(srv, 1));
  17203. std::string received;
  17204. auto server_thread = std::thread([&] {
  17205. auto sock = ::accept(srv, nullptr, nullptr);
  17206. if (sock == INVALID_SOCKET) { return; }
  17207. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17208. char buf[2048];
  17209. ssize_t n;
  17210. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17211. received.append(buf, static_cast<size_t>(n));
  17212. }
  17213. detail::close_socket(sock);
  17214. });
  17215. {
  17216. auto cli = Client("127.0.0.1", PORT + 1);
  17217. // "Z" sorts after the default headers, so writing straight to the socket
  17218. // would have sent the request line and those headers before the rejection.
  17219. auto handle =
  17220. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17221. EXPECT_FALSE(handle.is_valid());
  17222. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17223. }
  17224. server_thread.join();
  17225. detail::close_socket(srv);
  17226. EXPECT_TRUE(received.empty()) << received;
  17227. }
  17228. TEST(PathParamsTest, StaticMatch) {
  17229. const auto pattern = "/users/all";
  17230. detail::PathParamsMatcher matcher(pattern);
  17231. Request request;
  17232. request.path = "/users/all";
  17233. ASSERT_TRUE(matcher.match(request));
  17234. std::unordered_map<std::string, std::string> expected_params = {};
  17235. EXPECT_EQ(request.path_params, expected_params);
  17236. }
  17237. TEST(PathParamsTest, StaticMismatch) {
  17238. const auto pattern = "/users/all";
  17239. detail::PathParamsMatcher matcher(pattern);
  17240. Request request;
  17241. request.path = "/users/1";
  17242. ASSERT_FALSE(matcher.match(request));
  17243. }
  17244. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17245. const auto pattern = "/users/:id/subscriptions";
  17246. detail::PathParamsMatcher matcher(pattern);
  17247. Request request;
  17248. request.path = "/users/42/subscriptions";
  17249. ASSERT_TRUE(matcher.match(request));
  17250. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17251. EXPECT_EQ(request.path_params, expected_params);
  17252. }
  17253. TEST(PathParamsTest, SingleParamInTheEnd) {
  17254. const auto pattern = "/users/:id";
  17255. detail::PathParamsMatcher matcher(pattern);
  17256. Request request;
  17257. request.path = "/users/24";
  17258. ASSERT_TRUE(matcher.match(request));
  17259. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17260. EXPECT_EQ(request.path_params, expected_params);
  17261. }
  17262. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17263. const auto pattern = "/users/:id/";
  17264. detail::PathParamsMatcher matcher(pattern);
  17265. Request request;
  17266. request.path = "/users/42/";
  17267. ASSERT_TRUE(matcher.match(request));
  17268. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17269. EXPECT_EQ(request.path_params, expected_params);
  17270. }
  17271. TEST(PathParamsTest, EmptyParam) {
  17272. const auto pattern = "/users/:id/";
  17273. detail::PathParamsMatcher matcher(pattern);
  17274. Request request;
  17275. request.path = "/users//";
  17276. ASSERT_TRUE(matcher.match(request));
  17277. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17278. EXPECT_EQ(request.path_params, expected_params);
  17279. }
  17280. TEST(PathParamsTest, FragmentMismatch) {
  17281. const auto pattern = "/users/:id/";
  17282. detail::PathParamsMatcher matcher(pattern);
  17283. Request request;
  17284. request.path = "/admins/24/";
  17285. ASSERT_FALSE(matcher.match(request));
  17286. }
  17287. TEST(PathParamsTest, ExtraFragments) {
  17288. const auto pattern = "/users/:id";
  17289. detail::PathParamsMatcher matcher(pattern);
  17290. Request request;
  17291. request.path = "/users/42/subscriptions";
  17292. ASSERT_FALSE(matcher.match(request));
  17293. }
  17294. TEST(PathParamsTest, MissingTrailingParam) {
  17295. const auto pattern = "/users/:id";
  17296. detail::PathParamsMatcher matcher(pattern);
  17297. Request request;
  17298. request.path = "/users";
  17299. ASSERT_FALSE(matcher.match(request));
  17300. }
  17301. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17302. const auto pattern = "/users/:id/subscriptions";
  17303. detail::PathParamsMatcher matcher(pattern);
  17304. Request request;
  17305. request.path = "/users/subscriptions";
  17306. ASSERT_FALSE(matcher.match(request));
  17307. }
  17308. TEST(PathParamsTest, MultipleParams) {
  17309. const auto pattern = "/users/:userid/subscriptions/:subid";
  17310. detail::PathParamsMatcher matcher(pattern);
  17311. Request request;
  17312. request.path = "/users/42/subscriptions/2";
  17313. ASSERT_TRUE(matcher.match(request));
  17314. std::unordered_map<std::string, std::string> expected_params = {
  17315. {"userid", "42"}, {"subid", "2"}};
  17316. EXPECT_EQ(request.path_params, expected_params);
  17317. }
  17318. TEST(PathParamsTest, SequenceOfParams) {
  17319. const auto pattern = "/values/:x/:y/:z";
  17320. detail::PathParamsMatcher matcher(pattern);
  17321. Request request;
  17322. request.path = "/values/1/2/3";
  17323. ASSERT_TRUE(matcher.match(request));
  17324. std::unordered_map<std::string, std::string> expected_params = {
  17325. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17326. EXPECT_EQ(request.path_params, expected_params);
  17327. }
  17328. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17329. const auto pattern = "/prefix:suffix";
  17330. detail::PathParamsMatcher matcher(pattern);
  17331. Request request;
  17332. request.path = "/prefix:suffix";
  17333. ASSERT_TRUE(matcher.match(request));
  17334. const std::unordered_map<std::string, std::string> expected_params = {};
  17335. EXPECT_EQ(request.path_params, expected_params);
  17336. }
  17337. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17338. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17339. // calling thread's stack on a long enough path for a quantified pattern;
  17340. // RegexMatcher must refuse to run regex matching on paths beyond
  17341. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17342. detail::RegexMatcher matcher("/files/(.*)");
  17343. Request within_limit;
  17344. within_limit.path = "/files/" + std::string(10, 'A');
  17345. EXPECT_TRUE(matcher.match(within_limit));
  17346. Request over_limit;
  17347. over_limit.path =
  17348. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17349. EXPECT_FALSE(matcher.match(over_limit));
  17350. }
  17351. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17352. Server svr;
  17353. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17354. res.set_content("ok", "text/plain");
  17355. });
  17356. auto port = svr.bind_to_any_port(HOST);
  17357. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17358. auto se = detail::scope_exit([&] {
  17359. svr.stop();
  17360. thread.join();
  17361. ASSERT_FALSE(svr.is_running());
  17362. });
  17363. svr.wait_until_ready();
  17364. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17365. // request URI limit; this used to be able to crash the process.
  17366. std::string path =
  17367. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17368. std::string req = "GET " + path +
  17369. " HTTP/1.1\r\n"
  17370. "Host: " +
  17371. std::string(HOST) + ":" + std::to_string(port) +
  17372. "\r\n"
  17373. "Connection: close\r\n"
  17374. "\r\n";
  17375. std::string response;
  17376. ASSERT_TRUE(send_request(5, req, &response, port));
  17377. EXPECT_NE(std::string::npos, response.find("404"));
  17378. }
  17379. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17380. Server svr;
  17381. auto handler = [](const Request & /*req*/, Response &res) {
  17382. res.set_content("hit", "text/plain");
  17383. };
  17384. // No regex metacharacter, so this one is compared literally
  17385. svr.Get("/literal/route", handler);
  17386. // '.' is a regex metacharacter, so this one must keep regex semantics
  17387. svr.Get("/a.c", handler);
  17388. auto port = svr.bind_to_any_port(HOST);
  17389. std::thread t([&]() { svr.listen_after_bind(); });
  17390. auto se = detail::scope_exit([&] {
  17391. svr.stop();
  17392. t.join();
  17393. ASSERT_FALSE(svr.is_running());
  17394. });
  17395. svr.wait_until_ready();
  17396. Client cli(HOST, port);
  17397. struct {
  17398. const char *path;
  17399. int status;
  17400. } cases[] = {
  17401. {"/literal/route", StatusCode::OK_200},
  17402. {"/literal/routes", StatusCode::NotFound_404},
  17403. {"/literal/rout", StatusCode::NotFound_404},
  17404. {"/abc", StatusCode::OK_200},
  17405. {"/a.c", StatusCode::OK_200},
  17406. };
  17407. for (const auto &x : cases) {
  17408. auto res = cli.Get(x.path);
  17409. ASSERT_TRUE(res) << x.path;
  17410. EXPECT_EQ(x.status, res->status) << x.path;
  17411. }
  17412. }
  17413. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17414. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17415. // from exhausting the stack, so it must only constrain routes that actually
  17416. // run a regular expression. A literal route is matched by comparison and
  17417. // stays usable at any length.
  17418. Server svr;
  17419. const std::string pattern =
  17420. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17421. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17422. res.set_content("hit", "text/plain");
  17423. });
  17424. auto port = svr.bind_to_any_port(HOST);
  17425. std::thread t([&]() { svr.listen_after_bind(); });
  17426. auto se = detail::scope_exit([&] {
  17427. svr.stop();
  17428. t.join();
  17429. ASSERT_FALSE(svr.is_running());
  17430. });
  17431. svr.wait_until_ready();
  17432. Client cli(HOST, port);
  17433. auto res = cli.Get(pattern);
  17434. ASSERT_TRUE(res);
  17435. EXPECT_EQ(StatusCode::OK_200, res->status);
  17436. }
  17437. TEST(ParseUrlTest, VariousPatterns) {
  17438. {
  17439. detail::UrlComponents uc;
  17440. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17441. EXPECT_EQ("http", uc.scheme);
  17442. EXPECT_EQ("example.com", uc.host);
  17443. EXPECT_EQ("8080", uc.port);
  17444. EXPECT_EQ("/path", uc.path);
  17445. EXPECT_EQ("?q=1", uc.query);
  17446. }
  17447. {
  17448. detail::UrlComponents uc;
  17449. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17450. EXPECT_EQ("https", uc.scheme);
  17451. EXPECT_EQ("example.com", uc.host);
  17452. EXPECT_TRUE(uc.port.empty());
  17453. EXPECT_EQ("/path", uc.path);
  17454. }
  17455. {
  17456. detail::UrlComponents uc;
  17457. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17458. EXPECT_EQ("::1", uc.host);
  17459. EXPECT_EQ("8080", uc.port);
  17460. EXPECT_EQ("/path", uc.path);
  17461. }
  17462. {
  17463. detail::UrlComponents uc;
  17464. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17465. }
  17466. {
  17467. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17468. // the path while the connection still targets the bracketed host.
  17469. detail::UrlComponents uc;
  17470. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17471. }
  17472. {
  17473. detail::UrlComponents uc;
  17474. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17475. }
  17476. {
  17477. detail::UrlComponents uc;
  17478. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17479. EXPECT_EQ("::1", uc.host);
  17480. EXPECT_TRUE(uc.port.empty());
  17481. EXPECT_EQ("/path", uc.path);
  17482. }
  17483. {
  17484. detail::UrlComponents uc;
  17485. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17486. EXPECT_TRUE(uc.scheme.empty());
  17487. EXPECT_EQ("example.com", uc.host);
  17488. EXPECT_EQ("/path", uc.path);
  17489. EXPECT_EQ("?q=1", uc.query);
  17490. }
  17491. {
  17492. detail::UrlComponents uc;
  17493. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17494. EXPECT_TRUE(uc.host.empty());
  17495. EXPECT_EQ("/path", uc.path);
  17496. EXPECT_EQ("?q=1", uc.query);
  17497. }
  17498. {
  17499. detail::UrlComponents uc;
  17500. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17501. EXPECT_EQ("example.com", uc.host);
  17502. EXPECT_EQ("8080", uc.port);
  17503. }
  17504. {
  17505. // Unix socket path — must not be parsed as host
  17506. detail::UrlComponents uc;
  17507. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17508. EXPECT_TRUE(uc.host.empty());
  17509. }
  17510. {
  17511. detail::UrlComponents uc;
  17512. ASSERT_TRUE(detail::parse_url("", uc));
  17513. EXPECT_TRUE(uc.host.empty());
  17514. EXPECT_TRUE(uc.path.empty());
  17515. }
  17516. {
  17517. detail::UrlComponents uc;
  17518. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17519. }
  17520. {
  17521. detail::UrlComponents uc;
  17522. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17523. }
  17524. {
  17525. // Accepted by parse_url; callers restrict to http/https
  17526. detail::UrlComponents uc;
  17527. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17528. EXPECT_EQ("ftp", uc.scheme);
  17529. }
  17530. {
  17531. detail::UrlComponents uc;
  17532. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17533. }
  17534. {
  17535. detail::UrlComponents uc;
  17536. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17537. }
  17538. }
  17539. TEST(ParseUrlTest, FragmentHandling) {
  17540. {
  17541. detail::UrlComponents uc;
  17542. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17543. EXPECT_EQ("/path", uc.path);
  17544. EXPECT_TRUE(uc.query.empty());
  17545. }
  17546. {
  17547. detail::UrlComponents uc;
  17548. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17549. EXPECT_TRUE(uc.path.empty());
  17550. EXPECT_TRUE(uc.query.empty());
  17551. }
  17552. }
  17553. TEST(ParseUrlTest, UserinfoHandling) {
  17554. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17555. // parsers would see evil.com as the host.
  17556. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17557. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17558. for (auto url : urls) {
  17559. detail::UrlComponents uc;
  17560. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17561. }
  17562. }
  17563. TEST(ParseUrlTest, IPv6EdgeCases) {
  17564. {
  17565. detail::UrlComponents uc;
  17566. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17567. EXPECT_TRUE(uc.scheme.empty());
  17568. EXPECT_EQ("::1", uc.host);
  17569. EXPECT_EQ("8080", uc.port);
  17570. }
  17571. {
  17572. // Zone ID '%25' is not in [a-fA-F0-9:]
  17573. detail::UrlComponents uc;
  17574. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17575. }
  17576. }
  17577. TEST(ParseUrlTest, SchemeEdgeCases) {
  17578. {
  17579. detail::UrlComponents uc;
  17580. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17581. }
  17582. {
  17583. detail::UrlComponents uc;
  17584. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17585. }
  17586. {
  17587. detail::UrlComponents uc;
  17588. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17589. }
  17590. }
  17591. TEST(ParseUrlTest, PortEdgeCases) {
  17592. {
  17593. detail::UrlComponents uc;
  17594. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17595. EXPECT_TRUE(uc.port.empty());
  17596. EXPECT_EQ("/path", uc.path);
  17597. }
  17598. {
  17599. // parse_url accepts any port string; validation is done by parse_port
  17600. detail::UrlComponents uc;
  17601. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17602. EXPECT_EQ("abc", uc.port);
  17603. }
  17604. }
  17605. TEST(ParseUrlTest, WebSocketPatterns) {
  17606. {
  17607. detail::UrlComponents uc;
  17608. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17609. EXPECT_EQ("ws", uc.scheme);
  17610. EXPECT_EQ("echo.example.com", uc.host);
  17611. EXPECT_EQ("8080", uc.port);
  17612. EXPECT_EQ("/ws", uc.path);
  17613. }
  17614. {
  17615. detail::UrlComponents uc;
  17616. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17617. EXPECT_EQ("wss", uc.scheme);
  17618. EXPECT_EQ("echo.example.com", uc.host);
  17619. EXPECT_TRUE(uc.port.empty());
  17620. EXPECT_EQ("/ws", uc.path);
  17621. }
  17622. }
  17623. TEST(ParseUrlTest, QueryOnly) {
  17624. detail::UrlComponents uc;
  17625. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17626. EXPECT_TRUE(uc.host.empty());
  17627. EXPECT_TRUE(uc.path.empty());
  17628. EXPECT_EQ("?q=1&r=2", uc.query);
  17629. }
  17630. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17631. detail::UrlComponents uc;
  17632. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17633. EXPECT_TRUE(uc.scheme.empty());
  17634. EXPECT_EQ("example.com", uc.host);
  17635. EXPECT_EQ("443", uc.port);
  17636. EXPECT_EQ("/path", uc.path);
  17637. }
  17638. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17639. // If ipv6 regex working, regex match codepath is taken.
  17640. // else port will default to 80 in Client impl
  17641. int clientImplMagicPort = 80;
  17642. int port = 4321;
  17643. // above ports must be different to avoid false negative
  17644. EXPECT_NE(clientImplMagicPort, port);
  17645. std::string ipV6TestURL = "http://[ff06::c3]";
  17646. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17647. CLIENT_PRIVATE_KEY_FILE);
  17648. EXPECT_EQ(cli.port(), port);
  17649. }
  17650. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17651. auto file_path = "./www/dir/index.html";
  17652. auto dir_path = "./www/dir";
  17653. detail::FileStat stat_file(file_path);
  17654. EXPECT_TRUE(stat_file.is_file());
  17655. EXPECT_FALSE(stat_file.is_dir());
  17656. detail::FileStat stat_dir(dir_path);
  17657. EXPECT_FALSE(stat_dir.is_file());
  17658. EXPECT_TRUE(stat_dir.is_dir());
  17659. }
  17660. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17661. // IPv4 with default HTTP port (80)
  17662. EXPECT_EQ("example.com",
  17663. detail::make_host_and_port_string("example.com", 80, false));
  17664. // IPv4 with default HTTPS port (443)
  17665. EXPECT_EQ("example.com",
  17666. detail::make_host_and_port_string("example.com", 443, true));
  17667. // IPv4 with non-default HTTP port
  17668. EXPECT_EQ("example.com:8080",
  17669. detail::make_host_and_port_string("example.com", 8080, false));
  17670. // IPv4 with non-default HTTPS port
  17671. EXPECT_EQ("example.com:8443",
  17672. detail::make_host_and_port_string("example.com", 8443, true));
  17673. // IPv6 with default HTTP port (80)
  17674. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17675. // IPv6 with default HTTPS port (443)
  17676. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17677. // IPv6 with non-default HTTP port
  17678. EXPECT_EQ("[::1]:8080",
  17679. detail::make_host_and_port_string("::1", 8080, false));
  17680. // IPv6 with non-default HTTPS port
  17681. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17682. // IPv6 full address with default port
  17683. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17684. detail::make_host_and_port_string(
  17685. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17686. // IPv6 full address with non-default port
  17687. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17688. detail::make_host_and_port_string(
  17689. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17690. // IPv6 localhost with non-default port
  17691. EXPECT_EQ("[::1]:3000",
  17692. detail::make_host_and_port_string("::1", 3000, false));
  17693. // IPv6 with zone ID (link-local address) with default port
  17694. EXPECT_EQ("[fe80::1%eth0]",
  17695. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17696. // IPv6 with zone ID (link-local address) with non-default port
  17697. EXPECT_EQ("[fe80::1%eth0]:8080",
  17698. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17699. // Edge case: Port 443 with is_ssl=false (should add port)
  17700. EXPECT_EQ("example.com:443",
  17701. detail::make_host_and_port_string("example.com", 443, false));
  17702. // Edge case: Port 80 with is_ssl=true (should add port)
  17703. EXPECT_EQ("example.com:80",
  17704. detail::make_host_and_port_string("example.com", 80, true));
  17705. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17706. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17707. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17708. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17709. // Security fix: Already bracketed IPv6 should not get double brackets
  17710. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17711. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17712. EXPECT_EQ("[::1]:8080",
  17713. detail::make_host_and_port_string("[::1]", 8080, false));
  17714. EXPECT_EQ("[2001:db8::1]:8080",
  17715. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17716. EXPECT_EQ("[fe80::1%eth0]",
  17717. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17718. EXPECT_EQ("[fe80::1%eth0]:8080",
  17719. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17720. // Edge case: Empty host (should return as-is)
  17721. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17722. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17723. // This is a known limitation but shouldn't crash
  17724. EXPECT_EQ("[host:name]",
  17725. detail::make_host_and_port_string("host:name", 80, false));
  17726. // Port number edge cases (no validation, but should not crash)
  17727. EXPECT_EQ("example.com:0",
  17728. detail::make_host_and_port_string("example.com", 0, false));
  17729. EXPECT_EQ("example.com:-1",
  17730. detail::make_host_and_port_string("example.com", -1, false));
  17731. EXPECT_EQ("example.com:65535",
  17732. detail::make_host_and_port_string("example.com", 65535, false));
  17733. EXPECT_EQ("example.com:65536",
  17734. detail::make_host_and_port_string("example.com", 65536, false));
  17735. }
  17736. #ifdef CPPHTTPLIB_SSL_ENABLED
  17737. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17738. httplib::SSLClient cli("roblox.com", 443);
  17739. cli.set_follow_location(true);
  17740. auto res = cli.Get("/");
  17741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17742. EXPECT_EQ(StatusCode::OK_200, res->status);
  17743. }
  17744. #endif
  17745. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17746. Server svr;
  17747. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17748. EXPECT_EQ(res.status, 400);
  17749. });
  17750. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17751. auto se = detail::scope_exit([&] {
  17752. svr.stop();
  17753. thread.join();
  17754. ASSERT_FALSE(svr.is_running());
  17755. });
  17756. svr.wait_until_ready();
  17757. Client cli(HOST, PORT);
  17758. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17759. }
  17760. TEST(InvalidHeaderCharsTest, is_field_name) {
  17761. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17762. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17763. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17764. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17765. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17766. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17767. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17768. EXPECT_FALSE(detail::fields::is_field_name(""));
  17769. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17770. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17771. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17772. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17773. }
  17774. TEST(InvalidHeaderCharsTest, is_field_value) {
  17775. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17776. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17777. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17778. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17779. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17780. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17781. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17782. EXPECT_TRUE(detail::fields::is_field_value(""));
  17783. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17784. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17785. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17786. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17787. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17788. }
  17789. TEST(InvalidHeaderCharsTest, OnServer) {
  17790. Server svr;
  17791. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17792. std::string header = "Not Set";
  17793. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17794. res.set_header(header, "value");
  17795. res.set_content("Page Content Page Content", "text/plain");
  17796. });
  17797. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17798. std::string header = "Not Set";
  17799. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17800. res.set_header("X-Test", header);
  17801. res.set_content("Page Content Page Content", "text/plain");
  17802. });
  17803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17804. auto se = detail::scope_exit([&] {
  17805. svr.stop();
  17806. thread.join();
  17807. ASSERT_FALSE(svr.is_running());
  17808. });
  17809. svr.wait_until_ready();
  17810. Client cli(HOST, PORT);
  17811. {
  17812. auto res = cli.Get(
  17813. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17815. EXPECT_EQ("Page Content Page Content", res->body);
  17816. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17817. }
  17818. {
  17819. auto res = cli.Get(
  17820. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17822. EXPECT_EQ("Page Content Page Content", res->body);
  17823. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17824. }
  17825. }
  17826. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17827. auto handled = false;
  17828. Server svr;
  17829. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17830. thread t = thread([&] { svr.listen(HOST, PORT); });
  17831. auto se = detail::scope_exit([&] {
  17832. svr.stop();
  17833. t.join();
  17834. ASSERT_FALSE(svr.is_running());
  17835. ASSERT_FALSE(handled);
  17836. });
  17837. svr.wait_until_ready();
  17838. auto req = "POST /test HTTP/1.1\r\n"
  17839. "Content-Length: x\r\n"
  17840. "\r\n";
  17841. std::string response;
  17842. ASSERT_TRUE(send_request(1, req, &response));
  17843. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17844. response.substr(0, response.find("\r\n")));
  17845. }
  17846. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17847. // case-insensitive, and a server that receives a 100-continue expectation in
  17848. // an HTTP/1.0 request MUST ignore it.
  17849. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17850. std::string response;
  17851. ASSERT_TRUE(send_request(1, req, &response, port));
  17852. *got_100 = response.find("100 Continue") != std::string::npos;
  17853. }
  17854. class ExpectTokenTest : public ::testing::Test {
  17855. protected:
  17856. void SetUp() override {
  17857. svr_.Post("/p", [](const Request &, Response &res) {
  17858. res.set_content("ok", "text/plain");
  17859. });
  17860. port_ = svr_.bind_to_any_port(HOST);
  17861. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17862. svr_.wait_until_ready();
  17863. }
  17864. void TearDown() override {
  17865. svr_.stop();
  17866. if (thread_.joinable()) { thread_.join(); }
  17867. }
  17868. std::string request(const char *version, const char *expect_value) const {
  17869. return std::string("POST /p ") + version +
  17870. "\r\n"
  17871. "Host: localhost\r\n"
  17872. "Content-Length: 2\r\n"
  17873. "Connection: close\r\n"
  17874. "Expect: " +
  17875. expect_value +
  17876. "\r\n"
  17877. "\r\n"
  17878. "hi";
  17879. }
  17880. Server svr_;
  17881. int port_ = 0;
  17882. thread thread_;
  17883. };
  17884. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17885. bool got_100 = false;
  17886. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17887. EXPECT_TRUE(got_100);
  17888. }
  17889. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17890. bool got_100 = true;
  17891. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17892. EXPECT_FALSE(got_100);
  17893. }
  17894. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17895. bool got_100 = false;
  17896. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17897. EXPECT_TRUE(got_100);
  17898. }
  17899. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17900. bool got_100 = false;
  17901. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17902. EXPECT_TRUE(got_100);
  17903. }
  17904. // `100 Continue` is sent only when the server starts reading the body, so a
  17905. // request rejected before that never invites the client to send it. The
  17906. // requests below carry the expectation but withhold the body, as a client
  17907. // waiting for `100 Continue` would.
  17908. // A POST that expects `100 Continue` and withholds its two-byte body.
  17909. static std::string expect_headers_only(const std::string &path) {
  17910. return "POST " + path +
  17911. " HTTP/1.1\r\n"
  17912. "Host: localhost\r\n"
  17913. "Content-Length: 2\r\n"
  17914. "Expect: 100-continue\r\n"
  17915. "\r\n";
  17916. }
  17917. class ExpectLazyContinueTest : public ::testing::Test {
  17918. protected:
  17919. void SetUp() override {
  17920. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17921. if (req.path == "/pre-routing") {
  17922. res.status = StatusCode::Unauthorized_401;
  17923. return Server::HandlerResponse::Handled;
  17924. }
  17925. return Server::HandlerResponse::Unhandled;
  17926. });
  17927. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17928. if (req.matched_route == "/pre-request") {
  17929. res.status = StatusCode::Forbidden_403;
  17930. return Server::HandlerResponse::Handled;
  17931. }
  17932. return Server::HandlerResponse::Unhandled;
  17933. });
  17934. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17935. res.set_content("ok", "text/plain");
  17936. });
  17937. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17938. res.set_content("ok", "text/plain");
  17939. });
  17940. svr_.Post("/reader-used", [](const Request &, Response &res,
  17941. const ContentReader &content_reader) {
  17942. std::string body;
  17943. content_reader([&](const char *data, size_t len) {
  17944. body.append(data, len);
  17945. return true;
  17946. });
  17947. res.set_content(body, "text/plain");
  17948. });
  17949. svr_.Post("/reader-unused",
  17950. [](const Request &, Response &res, const ContentReader &) {
  17951. res.set_content("ignored", "text/plain");
  17952. });
  17953. port_ = svr_.bind_to_any_port(HOST);
  17954. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17955. svr_.wait_until_ready();
  17956. }
  17957. void TearDown() override {
  17958. svr_.stop();
  17959. if (thread_.joinable()) { thread_.join(); }
  17960. }
  17961. // Sends `req` and reads until the server closes the connection. Returns
  17962. // false if the read had to wait for the client-side timeout instead.
  17963. bool send_until_closed(const std::string &req, std::string *resp) const {
  17964. auto start = std::chrono::steady_clock::now();
  17965. if (!send_request(3, req, resp, port_)) { return false; }
  17966. auto elapsed = std::chrono::steady_clock::now() - start;
  17967. return elapsed < std::chrono::seconds(2);
  17968. }
  17969. // The final response comes without `100 Continue`, and the server closes
  17970. // the connection since the body may or may not follow.
  17971. void expect_final_without_interim(const std::string &path,
  17972. const char *status_line) const {
  17973. std::string resp;
  17974. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17975. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17976. EXPECT_EQ(0u, resp.find(status_line));
  17977. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17978. }
  17979. Server svr_;
  17980. int port_ = 0;
  17981. thread thread_;
  17982. };
  17983. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17984. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17985. }
  17986. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17987. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17988. }
  17989. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17990. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17991. }
  17992. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17993. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17994. }
  17995. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17996. // The body follows once `100 Continue` has had time to arrive.
  17997. auto req = expect_headers_only("/reader-used");
  17998. req.insert(req.size() - 2, "Connection: close\r\n");
  17999. std::string resp;
  18000. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18001. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18002. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18003. EXPECT_NE(std::string::npos, resp.find("hi"));
  18004. }
  18005. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18006. // Large enough for the client to add `Expect: 100-continue` itself.
  18007. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18008. std::atomic<bool> body_sent{false};
  18009. Client cli(HOST, port_);
  18010. auto res = cli.Post(
  18011. "/pre-request", length,
  18012. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18013. body_sent = true;
  18014. std::string chunk(len, 'x');
  18015. sink.write(chunk.data(), chunk.size());
  18016. return true;
  18017. },
  18018. "application/octet-stream");
  18019. ASSERT_TRUE(res);
  18020. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18021. EXPECT_FALSE(body_sent);
  18022. }
  18023. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18024. Server svr;
  18025. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18026. return StatusCode::ExpectationFailed_417;
  18027. });
  18028. svr.Post("/p", [](const Request &, Response &res) {
  18029. res.set_content("ok", "text/plain");
  18030. });
  18031. auto port = svr.bind_to_any_port(HOST);
  18032. thread t = thread([&] { svr.listen_after_bind(); });
  18033. auto se = detail::scope_exit([&] {
  18034. svr.stop();
  18035. t.join();
  18036. });
  18037. svr.wait_until_ready();
  18038. std::string resp;
  18039. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18040. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18041. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18042. // Exactly one response: the route handler must not run after the 417.
  18043. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18044. }
  18045. #ifndef _WIN32
  18046. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18047. static constexpr char reject[] = "Unauthorized";
  18048. static constexpr char accept[] = "Upload accepted";
  18049. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18050. Server svr;
  18051. svr.set_expect_100_continue_handler(
  18052. [](const Request & /*req*/, Response &res) {
  18053. res.status = StatusCode::Unauthorized_401;
  18054. res.set_content(reject, "text/plain");
  18055. return res.status;
  18056. });
  18057. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18058. res.set_content(accept, "text/plain");
  18059. });
  18060. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18061. auto se = detail::scope_exit([&] {
  18062. svr.stop();
  18063. thread.join();
  18064. ASSERT_FALSE(svr.is_running());
  18065. });
  18066. svr.wait_until_ready();
  18067. {
  18068. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18069. curl_easy_init(), &curl_easy_cleanup};
  18070. ASSERT_NE(curl, nullptr);
  18071. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18072. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18073. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18074. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18075. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18076. &curl_slist_free_all};
  18077. ASSERT_NE(list, nullptr);
  18078. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18079. struct read_data {
  18080. uint64_t read_size;
  18081. uint64_t total_size;
  18082. } data = {0, total_size};
  18083. using read_callback_t =
  18084. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18085. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18086. void *userdata) -> size_t {
  18087. read_data *d = (read_data *)userdata;
  18088. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18089. std::fill_n(ptr, size * nmemb, 'A');
  18090. d->read_size += size * nmemb;
  18091. return size * nmemb;
  18092. };
  18093. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18094. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18095. std::vector<char> buffer;
  18096. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18097. using write_callback_t =
  18098. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18099. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18100. void *userdata) -> size_t {
  18101. std::vector<char> *buf = (std::vector<char> *)userdata;
  18102. buf->reserve(buf->size() + size * nmemb + 1);
  18103. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18104. return size * nmemb;
  18105. };
  18106. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18107. {
  18108. const auto res = curl_easy_perform(curl.get());
  18109. ASSERT_EQ(res, CURLE_OK);
  18110. }
  18111. {
  18112. auto response_code = long{};
  18113. const auto res =
  18114. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18115. ASSERT_EQ(res, CURLE_OK);
  18116. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18117. }
  18118. {
  18119. auto dl = curl_off_t{};
  18120. const auto res =
  18121. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18122. ASSERT_EQ(res, CURLE_OK);
  18123. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18124. }
  18125. {
  18126. buffer.push_back('\0');
  18127. ASSERT_STRCASEEQ(buffer.data(), reject);
  18128. }
  18129. }
  18130. }
  18131. #endif
  18132. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18133. // Regression test for #2458.
  18134. //
  18135. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18136. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18137. // ticket can make the client socket spuriously readable during the
  18138. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18139. // the client withholds the body and then blocks reading a response that never
  18140. // comes, failing with `Failed to read connection`.
  18141. //
  18142. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18143. // within the timeout. This raw OpenSSL server deliberately never sends
  18144. // `100 Continue`; the client must still deliver the body and receive 200.
  18145. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18146. signal(SIGPIPE, SIG_IGN);
  18147. const auto port = PORT + 4;
  18148. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18149. ASSERT_NE(srv, INVALID_SOCKET);
  18150. int opt = 1;
  18151. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18152. sockaddr_in addr{};
  18153. addr.sin_family = AF_INET;
  18154. addr.sin_port = htons(static_cast<uint16_t>(port));
  18155. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18156. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18157. ASSERT_EQ(0, ::listen(srv, 1));
  18158. std::atomic<size_t> server_body_bytes{0};
  18159. auto server_thread = std::thread([&] {
  18160. sockaddr_in cli_addr{};
  18161. socklen_t cli_len = sizeof(cli_addr);
  18162. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18163. if (cli == INVALID_SOCKET) { return; }
  18164. // Bound the lifetime of the server side so a buggy client (which never
  18165. // sends the body) cannot make this thread block forever on join.
  18166. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18167. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18168. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18169. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18170. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18171. SSL *ssl = SSL_new(ctx);
  18172. SSL_set_fd(ssl, static_cast<int>(cli));
  18173. if (SSL_accept(ssl) > 0) {
  18174. // Read the request headers. Reading here also flushes the TLS 1.3
  18175. // session tickets to the client. Deliberately do NOT send
  18176. // `100 Continue`.
  18177. std::string buf;
  18178. char tmp[1024];
  18179. while (buf.find("\r\n\r\n") == std::string::npos) {
  18180. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18181. if (n <= 0) { break; }
  18182. buf.append(tmp, static_cast<size_t>(n));
  18183. }
  18184. // A correct client sends the body now; count what arrives.
  18185. auto pos = buf.find("\r\n\r\n");
  18186. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18187. while (body < 4096) {
  18188. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18189. if (n <= 0) { break; }
  18190. body += static_cast<size_t>(n);
  18191. }
  18192. server_body_bytes = body;
  18193. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18194. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18195. SSL_shutdown(ssl);
  18196. }
  18197. SSL_free(ssl);
  18198. detail::close_socket(cli);
  18199. SSL_CTX_free(ctx);
  18200. });
  18201. auto se = detail::scope_exit([&] {
  18202. server_thread.join();
  18203. detail::close_socket(srv);
  18204. });
  18205. SSLClient cli("127.0.0.1", port);
  18206. cli.enable_server_certificate_verification(false);
  18207. cli.set_connection_timeout(5, 0);
  18208. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18209. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18210. std::string body(4096, 'A');
  18211. auto res = cli.Put("/api/test", body, "application/json");
  18212. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18213. EXPECT_EQ(StatusCode::OK_200, res->status);
  18214. EXPECT_EQ(body.size(), server_body_bytes.load());
  18215. }
  18216. #endif
  18217. template <typename S, typename C>
  18218. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18219. svr.Get("/stream", [&](const Request &, Response &res) {
  18220. auto data = new std::string("01234567890123456789");
  18221. res.set_content_provider(
  18222. data->size(), "text/plain",
  18223. [&, data](size_t offset, size_t length, DataSink &sink) {
  18224. const size_t DATA_CHUNK_SIZE = 4;
  18225. const auto &d = *data;
  18226. std::this_thread::sleep_for(std::chrono::seconds(1));
  18227. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18228. return true;
  18229. },
  18230. [data](bool success) {
  18231. EXPECT_FALSE(success);
  18232. delete data;
  18233. });
  18234. });
  18235. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18236. auto i = new size_t(0);
  18237. res.set_content_provider(
  18238. "text/plain",
  18239. [i](size_t, DataSink &sink) {
  18240. if (*i < 5) {
  18241. std::this_thread::sleep_for(std::chrono::seconds(1));
  18242. sink.write("abcd", 4);
  18243. (*i)++;
  18244. } else {
  18245. sink.done();
  18246. }
  18247. return true;
  18248. },
  18249. [i](bool success) {
  18250. EXPECT_FALSE(success);
  18251. delete i;
  18252. });
  18253. });
  18254. svr.Get("/chunked", [&](const Request &, Response &res) {
  18255. auto i = new size_t(0);
  18256. res.set_chunked_content_provider(
  18257. "text/plain",
  18258. [i](size_t, DataSink &sink) {
  18259. if (*i < 5) {
  18260. std::this_thread::sleep_for(std::chrono::seconds(1));
  18261. sink.os << "abcd";
  18262. (*i)++;
  18263. } else {
  18264. sink.done();
  18265. }
  18266. return true;
  18267. },
  18268. [i](bool success) {
  18269. EXPECT_FALSE(success);
  18270. delete i;
  18271. });
  18272. });
  18273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18274. auto se = detail::scope_exit([&] {
  18275. svr.stop();
  18276. listen_thread.join();
  18277. ASSERT_FALSE(svr.is_running());
  18278. });
  18279. svr.wait_until_ready();
  18280. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18281. {
  18282. auto start = std::chrono::steady_clock::now();
  18283. auto res = cli.Get("/stream");
  18284. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18285. std::chrono::steady_clock::now() - start)
  18286. .count();
  18287. ASSERT_FALSE(res);
  18288. EXPECT_EQ(Error::Read, res.error());
  18289. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18290. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18291. }
  18292. {
  18293. auto start = std::chrono::steady_clock::now();
  18294. auto res = cli.Get("/stream_without_length");
  18295. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18296. std::chrono::steady_clock::now() - start)
  18297. .count();
  18298. ASSERT_FALSE(res);
  18299. EXPECT_EQ(Error::Read, res.error());
  18300. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18301. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18302. }
  18303. {
  18304. auto start = std::chrono::steady_clock::now();
  18305. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18306. EXPECT_EQ("abcd", string(data, data_length));
  18307. return true;
  18308. });
  18309. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18310. std::chrono::steady_clock::now() - start)
  18311. .count();
  18312. ASSERT_FALSE(res);
  18313. EXPECT_EQ(Error::Read, res.error());
  18314. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18315. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18316. }
  18317. }
  18318. TEST(MaxTimeoutTest, ContentStream) {
  18319. time_t timeout = 2000;
  18320. time_t threshold = 200;
  18321. Server svr;
  18322. Client cli("localhost", PORT);
  18323. max_timeout_test(svr, cli, timeout, threshold);
  18324. }
  18325. #ifdef CPPHTTPLIB_SSL_ENABLED
  18326. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18327. time_t timeout = 2000;
  18328. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18330. SSLClient cli("localhost", PORT);
  18331. cli.enable_server_certificate_verification(false);
  18332. max_timeout_test(svr, cli, timeout, threshold);
  18333. }
  18334. #endif
  18335. class EventDispatcher {
  18336. public:
  18337. EventDispatcher() {}
  18338. bool wait_event(DataSink *sink) {
  18339. unique_lock<mutex> lk(m_);
  18340. int id = id_;
  18341. // Wait with timeout to prevent hanging if client disconnects
  18342. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18343. [&] { return cid_ == id; })) {
  18344. return false; // Timeout occurred
  18345. }
  18346. sink->write(message_.data(), message_.size());
  18347. return true;
  18348. }
  18349. void send_event(const string &message) {
  18350. lock_guard<mutex> lk(m_);
  18351. cid_ = id_++;
  18352. message_ = message;
  18353. cv_.notify_all();
  18354. }
  18355. private:
  18356. mutex m_;
  18357. condition_variable cv_;
  18358. atomic_int id_{0};
  18359. atomic_int cid_{-1};
  18360. string message_;
  18361. };
  18362. TEST(ClientInThreadTest, Issue2068) {
  18363. EventDispatcher ed;
  18364. Server svr;
  18365. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18366. res.set_chunked_content_provider("text/event-stream",
  18367. [&](size_t /*offset*/, DataSink &sink) {
  18368. return ed.wait_event(&sink);
  18369. });
  18370. });
  18371. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18372. svr.wait_until_ready();
  18373. thread event_thread([&] {
  18374. int id = 0;
  18375. while (svr.is_running()) {
  18376. this_thread::sleep_for(chrono::milliseconds(500));
  18377. std::stringstream ss;
  18378. ss << "data: " << id << "\n\n";
  18379. ed.send_event(ss.str());
  18380. id++;
  18381. }
  18382. });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. listen_thread.join();
  18386. event_thread.join();
  18387. ASSERT_FALSE(svr.is_running());
  18388. });
  18389. {
  18390. auto client = detail::make_unique<Client>(HOST, PORT);
  18391. client->set_read_timeout(std::chrono::minutes(10));
  18392. std::atomic<bool> stop{false};
  18393. std::thread t([&] {
  18394. client->Get("/event1",
  18395. [&](const char *, size_t) -> bool { return !stop; });
  18396. });
  18397. std::this_thread::sleep_for(std::chrono::seconds(2));
  18398. stop = true;
  18399. client->stop();
  18400. t.join();
  18401. // Reset client after thread has finished
  18402. client.reset();
  18403. }
  18404. }
  18405. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18406. auto handled = false;
  18407. Server svr;
  18408. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18410. auto se = detail::scope_exit([&] {
  18411. svr.stop();
  18412. t.join();
  18413. ASSERT_FALSE(svr.is_running());
  18414. ASSERT_FALSE(handled);
  18415. });
  18416. svr.wait_until_ready();
  18417. // Two Content-Length headers with different values — must be rejected
  18418. auto req = "POST /test HTTP/1.1\r\n"
  18419. "Content-Length: 5\r\n"
  18420. "Content-Length: 10\r\n"
  18421. "\r\n"
  18422. "hello";
  18423. std::string response;
  18424. ASSERT_TRUE(send_request(1, req, &response));
  18425. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18426. response.substr(0, response.find("\r\n")));
  18427. }
  18428. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18429. auto handled = false;
  18430. Server svr;
  18431. svr.Post("/test", [&](const Request &, Response &res) {
  18432. handled = true;
  18433. res.set_content("ok", "text/plain");
  18434. });
  18435. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18436. auto se = detail::scope_exit([&] {
  18437. svr.stop();
  18438. t.join();
  18439. ASSERT_FALSE(svr.is_running());
  18440. ASSERT_TRUE(handled);
  18441. });
  18442. svr.wait_until_ready();
  18443. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18444. auto req = "POST /test HTTP/1.1\r\n"
  18445. "Host: localhost\r\n"
  18446. "Content-Length: 5\r\n"
  18447. "Content-Length: 5\r\n"
  18448. "\r\n"
  18449. "hello";
  18450. std::string response;
  18451. ASSERT_TRUE(send_request(1, req, &response));
  18452. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18453. }
  18454. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18455. Server svr;
  18456. svr.Get("/test", [](const Request &, Response &res) {
  18457. res.set_content("ok", "text/plain");
  18458. });
  18459. auto port = svr.bind_to_any_port(HOST);
  18460. thread t = thread([&] { svr.listen_after_bind(); });
  18461. auto se = detail::scope_exit([&] {
  18462. svr.stop();
  18463. t.join();
  18464. ASSERT_FALSE(svr.is_running());
  18465. });
  18466. svr.wait_until_ready();
  18467. auto status_line = [&](const std::string &host_lines) {
  18468. std::string res;
  18469. send_request(
  18470. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18471. &res, port);
  18472. return res.substr(0, res.find("\r\n"));
  18473. };
  18474. const char *accepted[] = {
  18475. "Host: localhost\r\n",
  18476. "Host: a.example:8080\r\n",
  18477. "Host: my_service\r\n",
  18478. "Host: [::1]:8080\r\n",
  18479. "Host: [fe80::1%25eth0]\r\n",
  18480. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18481. };
  18482. for (auto host_lines : accepted) {
  18483. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18484. }
  18485. const char *rejected[] = {
  18486. "Host: a.example\r\nHost: b.example\r\n",
  18487. "Host: a.example\r\nHost: a.example\r\n",
  18488. "Host: a@b.example\r\n",
  18489. "Host: a.example/b\r\n",
  18490. "Host: a.example\\b\r\n",
  18491. "Host: a.example?b\r\n",
  18492. "Host: a.example#b\r\n",
  18493. "Host: a.example b.example\r\n",
  18494. };
  18495. for (auto host_lines : rejected) {
  18496. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18497. << host_lines;
  18498. }
  18499. }
  18500. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18501. Server svr;
  18502. svr.Get("/", [](const Request &req, Response &res) {
  18503. EXPECT_EQ(2U, req.trailers.size());
  18504. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18505. // Denied
  18506. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18507. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18508. // Accepted
  18509. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18510. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18511. EXPECT_TRUE(req.has_trailer("X-World"));
  18512. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18513. res.set_content("ok", "text/plain");
  18514. });
  18515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18516. auto se = detail::scope_exit([&] {
  18517. svr.stop();
  18518. t.join();
  18519. ASSERT_FALSE(svr.is_running());
  18520. });
  18521. svr.wait_until_ready();
  18522. const std::string req = "GET / HTTP/1.1\r\n"
  18523. "Transfer-Encoding: chunked\r\n"
  18524. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18525. "\r\n"
  18526. "0\r\n"
  18527. "Content-Length: 10\r\n"
  18528. "Host: internal.local\r\n"
  18529. "Content-Type: malicious/content\r\n"
  18530. "Cookie: any\r\n"
  18531. "Set-Cookie: any\r\n"
  18532. "X-Forwarded-For: attacker.com\r\n"
  18533. "X-Real-Ip: 1.1.1.1\r\n"
  18534. "X-Hello: hello\r\n"
  18535. "X-World: world\r\n"
  18536. "\r\n";
  18537. std::string res;
  18538. ASSERT_TRUE(send_request(1, req, &res));
  18539. }
  18540. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18541. // several field lines, and the combined value is what has to be parsed. A
  18542. // Trailer field split across lines therefore declares every name it lists;
  18543. // reading only the first line silently drops the trailers the later lines
  18544. // declare. The prohibited-trailer filter still applies to every line.
  18545. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18546. Server svr;
  18547. size_t observed_trailer_count = 0;
  18548. std::string observed_hello;
  18549. std::string observed_world;
  18550. bool observed_content_length = true;
  18551. svr.Get("/", [&](const Request &req, Response &res) {
  18552. observed_trailer_count = req.trailers.size();
  18553. observed_hello = req.get_trailer_value("X-Hello");
  18554. observed_world = req.get_trailer_value("X-World");
  18555. observed_content_length = req.has_trailer("Content-Length");
  18556. res.set_content("ok", "text/plain");
  18557. });
  18558. auto port = svr.bind_to_any_port(HOST);
  18559. thread t = thread([&]() { svr.listen_after_bind(); });
  18560. auto se = detail::scope_exit([&] {
  18561. svr.stop();
  18562. t.join();
  18563. ASSERT_FALSE(svr.is_running());
  18564. });
  18565. svr.wait_until_ready();
  18566. const std::string req = "GET / HTTP/1.1\r\n"
  18567. "Host: localhost\r\n"
  18568. "Transfer-Encoding: chunked\r\n"
  18569. "Trailer: X-Hello\r\n"
  18570. "Trailer: X-World, Content-Length\r\n"
  18571. "\r\n"
  18572. "0\r\n"
  18573. "X-Hello: hello\r\n"
  18574. "X-World: world\r\n"
  18575. "Content-Length: 10\r\n"
  18576. "\r\n";
  18577. std::string res;
  18578. ASSERT_TRUE(send_request(1, req, &res, port));
  18579. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18580. // Accepted: both field lines contribute to the declared set
  18581. EXPECT_EQ(2U, observed_trailer_count);
  18582. EXPECT_EQ(observed_hello, "hello");
  18583. EXPECT_EQ(observed_world, "world");
  18584. // Denied: a prohibited name stays prohibited on a later field line
  18585. EXPECT_FALSE(observed_content_length);
  18586. }
  18587. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18588. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18589. // unbounded run of fields that are never declared, because the counter would
  18590. // only advance for declared fields.
  18591. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18592. Server svr;
  18593. bool handler_called = false;
  18594. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18595. handler_called = true;
  18596. res.set_content("ok", "text/plain");
  18597. });
  18598. auto port = svr.bind_to_any_port(HOST);
  18599. thread t = thread([&]() { svr.listen_after_bind(); });
  18600. auto se = detail::scope_exit([&] {
  18601. svr.stop();
  18602. t.join();
  18603. ASSERT_FALSE(svr.is_running());
  18604. });
  18605. svr.wait_until_ready();
  18606. // Declare nothing, then send far more undeclared trailer fields than the
  18607. // header-count limit. Parsing must stop and reject the request rather than
  18608. // read every line.
  18609. std::string req = "GET / HTTP/1.1\r\n"
  18610. "Transfer-Encoding: chunked\r\n"
  18611. "\r\n"
  18612. "0\r\n";
  18613. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18614. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18615. }
  18616. req += "\r\n";
  18617. std::string res;
  18618. ASSERT_TRUE(send_request(1, req, &res, port));
  18619. // The request is rejected before the handler runs.
  18620. EXPECT_FALSE(handler_called);
  18621. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18622. }
  18623. // The set of declared trailer names is capped so a peer cannot grow it without
  18624. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18625. // declared past the cap is not honored, even if the field is actually sent.
  18626. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18627. Server svr;
  18628. // One name inside the cap and one past it, so the test tracks the cap rather
  18629. // than a fixed count.
  18630. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18631. const std::string within_cap_name = "X-T-0";
  18632. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18633. bool observed_within_cap = false;
  18634. bool observed_past_cap = false;
  18635. svr.Get("/", [&](const Request &req, Response &res) {
  18636. observed_within_cap = req.has_trailer(within_cap_name);
  18637. observed_past_cap = req.has_trailer(past_cap_name);
  18638. res.set_content("ok", "text/plain");
  18639. });
  18640. auto port = svr.bind_to_any_port(HOST);
  18641. thread t = thread([&]() { svr.listen_after_bind(); });
  18642. auto se = detail::scope_exit([&] {
  18643. svr.stop();
  18644. t.join();
  18645. ASSERT_FALSE(svr.is_running());
  18646. });
  18647. svr.wait_until_ready();
  18648. // Declare more trailer names than the cap in a single Trailer field, then
  18649. // actually send the first (within the cap) and the last (past it).
  18650. std::string trailer_decl = "Trailer: ";
  18651. for (int i = 0; i < declared_count; i++) {
  18652. if (i != 0) { trailer_decl += ", "; }
  18653. trailer_decl += "X-T-" + std::to_string(i);
  18654. }
  18655. trailer_decl += "\r\n";
  18656. const std::string req = "GET / HTTP/1.1\r\n"
  18657. "Host: localhost\r\n"
  18658. "Transfer-Encoding: chunked\r\n" +
  18659. trailer_decl +
  18660. "\r\n"
  18661. "0\r\n" +
  18662. within_cap_name + ": a\r\n" + past_cap_name +
  18663. ": b\r\n"
  18664. "\r\n";
  18665. std::string res;
  18666. ASSERT_TRUE(send_request(1, req, &res, port));
  18667. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18668. // A name within the cap is honored; one declared past the cap is dropped.
  18669. EXPECT_TRUE(observed_within_cap);
  18670. EXPECT_FALSE(observed_past_cap);
  18671. }
  18672. // A direct client that is not listed in trusted_proxies must not be able to
  18673. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18674. // the peer address on the actual TCP connection determines whether the
  18675. // header is honored.
  18676. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18677. Server svr;
  18678. // Deliberately does NOT include the loopback address the test client
  18679. // actually connects from, so the direct connection is not a trusted proxy.
  18680. svr.set_trusted_proxies({"203.0.113.66"});
  18681. std::string observed_remote_addr;
  18682. svr.Get("/ip", [&](const Request &req, Response &res) {
  18683. observed_remote_addr = req.remote_addr;
  18684. res.set_content("ok", "text/plain");
  18685. });
  18686. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18687. auto se = detail::scope_exit([&] {
  18688. svr.stop();
  18689. t.join();
  18690. ASSERT_FALSE(svr.is_running());
  18691. });
  18692. svr.wait_until_ready();
  18693. Client cli(HOST, PORT);
  18694. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18696. EXPECT_EQ(StatusCode::OK_200, res->status);
  18697. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18698. // ignored entirely and the real connection-level address retained.
  18699. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18700. observed_remote_addr == "127.0.0.1");
  18701. }
  18702. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18703. Server svr;
  18704. std::string observed_remote_addr;
  18705. std::string observed_xff;
  18706. svr.Get("/ip", [&](const Request &req, Response &res) {
  18707. observed_remote_addr = req.remote_addr;
  18708. observed_xff = req.get_header_value("X-Forwarded-For");
  18709. res.set_content("ok", "text/plain");
  18710. });
  18711. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18712. auto se = detail::scope_exit([&] {
  18713. svr.stop();
  18714. t.join();
  18715. ASSERT_FALSE(svr.is_running());
  18716. });
  18717. svr.wait_until_ready();
  18718. Client cli(HOST, PORT);
  18719. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18721. EXPECT_EQ(StatusCode::OK_200, res->status);
  18722. EXPECT_EQ(observed_xff, "203.0.113.66");
  18723. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18724. observed_remote_addr == "127.0.0.1");
  18725. }
  18726. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18727. Server svr;
  18728. svr.set_trusted_proxies({"203.0.113.66"});
  18729. std::string observed_remote_addr;
  18730. std::string observed_xff;
  18731. svr.Get("/ip", [&](const Request &req, Response &res) {
  18732. observed_remote_addr = req.remote_addr;
  18733. observed_xff = req.get_header_value("X-Forwarded-For");
  18734. res.set_content("ok", "text/plain");
  18735. });
  18736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18737. auto se = detail::scope_exit([&] {
  18738. svr.stop();
  18739. t.join();
  18740. ASSERT_FALSE(svr.is_running());
  18741. });
  18742. svr.wait_until_ready();
  18743. Client cli(HOST, PORT);
  18744. auto res = cli.Get("/ip");
  18745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18746. EXPECT_EQ(StatusCode::OK_200, res->status);
  18747. EXPECT_EQ(observed_xff, "");
  18748. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18749. observed_remote_addr == "127.0.0.1");
  18750. }
  18751. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18752. Server svr;
  18753. // Include the loopback address the test client actually connects from, so
  18754. // the direct connection itself is recognized as the trusted proxy hop.
  18755. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18756. std::string observed_remote_addr;
  18757. std::string observed_xff;
  18758. svr.Get("/ip", [&](const Request &req, Response &res) {
  18759. observed_remote_addr = req.remote_addr;
  18760. observed_xff = req.get_header_value("X-Forwarded-For");
  18761. res.set_content("ok", "text/plain");
  18762. });
  18763. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18764. auto se = detail::scope_exit([&] {
  18765. svr.stop();
  18766. t.join();
  18767. ASSERT_FALSE(svr.is_running());
  18768. });
  18769. svr.wait_until_ready();
  18770. Client cli(HOST, PORT);
  18771. auto res = cli.Get(
  18772. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18774. EXPECT_EQ(StatusCode::OK_200, res->status);
  18775. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18776. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18777. }
  18778. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18779. Server svr;
  18780. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18781. std::string observed_remote_addr;
  18782. std::string observed_xff;
  18783. svr.Get("/ip", [&](const Request &req, Response &res) {
  18784. observed_remote_addr = req.remote_addr;
  18785. observed_xff = req.get_header_value("X-Forwarded-For");
  18786. res.set_content("ok", "text/plain");
  18787. });
  18788. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18789. auto se = detail::scope_exit([&] {
  18790. svr.stop();
  18791. t.join();
  18792. ASSERT_FALSE(svr.is_running());
  18793. });
  18794. svr.wait_until_ready();
  18795. Client cli(HOST, PORT);
  18796. auto res = cli.Get(
  18797. "/ip",
  18798. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18800. EXPECT_EQ(StatusCode::OK_200, res->status);
  18801. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18802. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18803. }
  18804. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18805. Server svr;
  18806. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18807. std::string observed_remote_addr;
  18808. std::string observed_xff;
  18809. svr.Get("/ip", [&](const Request &req, Response &res) {
  18810. observed_remote_addr = req.remote_addr;
  18811. observed_xff = req.get_header_value("X-Forwarded-For");
  18812. res.set_content("ok", "text/plain");
  18813. });
  18814. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18815. auto se = detail::scope_exit([&] {
  18816. svr.stop();
  18817. t.join();
  18818. ASSERT_FALSE(svr.is_running());
  18819. });
  18820. svr.wait_until_ready();
  18821. Client cli(HOST, PORT);
  18822. auto res = cli.Get(
  18823. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18825. EXPECT_EQ(StatusCode::OK_200, res->status);
  18826. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18827. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18828. // and must not be selected.
  18829. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18830. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18831. }
  18832. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18833. Server svr;
  18834. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18835. std::string observed_remote_addr;
  18836. svr.Get("/ip", [&](const Request &req, Response &res) {
  18837. observed_remote_addr = req.remote_addr;
  18838. res.set_content("ok", "text/plain");
  18839. });
  18840. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18841. auto se = detail::scope_exit([&] {
  18842. svr.stop();
  18843. t.join();
  18844. ASSERT_FALSE(svr.is_running());
  18845. });
  18846. svr.wait_until_ready();
  18847. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18848. // a forged address and the trusted proxy's own address; the forged value must
  18849. // not win over the address the trusted proxy actually recorded.
  18850. Client cli(HOST, PORT);
  18851. auto res = cli.Get(
  18852. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18854. EXPECT_EQ(StatusCode::OK_200, res->status);
  18855. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18856. }
  18857. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18858. Server svr;
  18859. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18860. std::string observed_remote_addr;
  18861. std::string observed_xff;
  18862. svr.Get("/ip", [&](const Request &req, Response &res) {
  18863. observed_remote_addr = req.remote_addr;
  18864. observed_xff = req.get_header_value("X-Forwarded-For");
  18865. res.set_content("ok", "text/plain");
  18866. });
  18867. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18868. auto se = detail::scope_exit([&] {
  18869. svr.stop();
  18870. t.join();
  18871. ASSERT_FALSE(svr.is_running());
  18872. });
  18873. svr.wait_until_ready();
  18874. Client cli(HOST, PORT);
  18875. auto res = cli.Get(
  18876. "/ip",
  18877. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18879. EXPECT_EQ(StatusCode::OK_200, res->status);
  18880. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18881. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18882. }
  18883. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18884. Server svr;
  18885. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18886. std::string observed_remote_addr;
  18887. std::string observed_xff;
  18888. svr.Get("/ip", [&](const Request &req, Response &res) {
  18889. observed_remote_addr = req.remote_addr;
  18890. observed_xff = req.get_header_value("X-Forwarded-For");
  18891. res.set_content("ok", "text/plain");
  18892. });
  18893. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18894. auto se = detail::scope_exit([&] {
  18895. svr.stop();
  18896. t.join();
  18897. ASSERT_FALSE(svr.is_running());
  18898. });
  18899. svr.wait_until_ready();
  18900. std::string raw_req =
  18901. "GET /ip HTTP/1.1\r\n"
  18902. "Host: localhost\r\n"
  18903. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18904. "Connection: close\r\n"
  18905. "\r\n";
  18906. std::string out;
  18907. ASSERT_TRUE(send_request(5, raw_req, &out));
  18908. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18909. // Header parser trims surrounding whitespace of the header value
  18910. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18911. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18912. }
  18913. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18914. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18915. // their own X-Forwarded-For as a separate field line rather than extending the
  18916. // one the client sent, so every occurrence has to be taken into account.
  18917. // Reading only the first one hands back the address the client chose.
  18918. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18919. Server svr;
  18920. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18921. std::string observed_remote_addr;
  18922. size_t observed_xff_count = 0;
  18923. svr.Get("/ip", [&](const Request &req, Response &res) {
  18924. observed_remote_addr = req.remote_addr;
  18925. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18926. res.set_content("ok", "text/plain");
  18927. });
  18928. auto port = svr.bind_to_any_port(HOST);
  18929. thread t = thread([&]() { svr.listen_after_bind(); });
  18930. auto se = detail::scope_exit([&] {
  18931. svr.stop();
  18932. t.join();
  18933. ASSERT_FALSE(svr.is_running());
  18934. });
  18935. svr.wait_until_ready();
  18936. // The client supplies the first field line; the trusted proxy appends the
  18937. // address it observed as a second one.
  18938. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18939. "Host: localhost\r\n"
  18940. "X-Forwarded-For: 1.2.3.4\r\n"
  18941. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18942. "Connection: close\r\n"
  18943. "\r\n";
  18944. std::string out;
  18945. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18946. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18947. EXPECT_EQ(observed_xff_count, 2U);
  18948. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18949. // The same chain spread over one field line per hop derives the same client
  18950. // address, i.e. the split and the comma-joined representations agree.
  18951. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18952. "Host: localhost\r\n"
  18953. "X-Forwarded-For: 1.2.3.4\r\n"
  18954. "X-Forwarded-For: 198.51.100.23\r\n"
  18955. "X-Forwarded-For: 192.0.2.45\r\n"
  18956. "Connection: close\r\n"
  18957. "\r\n";
  18958. out.clear();
  18959. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18960. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18961. EXPECT_EQ(observed_xff_count, 3U);
  18962. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18963. }
  18964. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18965. // crash the server (it used to call front() on an empty vector inside
  18966. // get_client_ip). The connection-level remote address must be retained instead.
  18967. static void run_malformed_xff_test(const std::string &xff_value) {
  18968. Server svr;
  18969. svr.set_trusted_proxies({"192.0.2.45"});
  18970. std::string observed_remote_addr;
  18971. svr.Get("/ip", [&](const Request &req, Response &res) {
  18972. observed_remote_addr = req.remote_addr;
  18973. res.set_content("ok", "text/plain");
  18974. });
  18975. int port = 0;
  18976. thread t = thread([&]() {
  18977. port = svr.bind_to_any_port(HOST);
  18978. svr.listen_after_bind();
  18979. });
  18980. auto se = detail::scope_exit([&] {
  18981. svr.stop();
  18982. t.join();
  18983. ASSERT_FALSE(svr.is_running());
  18984. });
  18985. svr.wait_until_ready();
  18986. Client cli(HOST, port);
  18987. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18989. EXPECT_EQ(StatusCode::OK_200, res->status);
  18990. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18991. observed_remote_addr == "127.0.0.1");
  18992. }
  18993. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18994. run_malformed_xff_test("");
  18995. }
  18996. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18997. run_malformed_xff_test(",");
  18998. }
  18999. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19000. run_malformed_xff_test(", , ,");
  19001. }
  19002. // The same rule applies to Accept: a request whose acceptable types are spread
  19003. // over several field lines must be negotiated against all of them.
  19004. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19005. // case-insensitive connection options. Comparing the whole field value against
  19006. // one option misses a client that sends several of them, and misses every
  19007. // casing but the one written in the comparison.
  19008. //
  19009. // Sends req, reads the response, then reuses the same socket for a second
  19010. // request to find out whether the server kept the connection.
  19011. static void probe_connection_reuse(int port, const std::string &req,
  19012. bool *announced_close, bool *reusable) {
  19013. auto error = Error::Success;
  19014. auto sock = detail::create_client_socket(
  19015. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19016. /*connection_timeout_sec=*/5, 0,
  19017. /*read_timeout_sec=*/1, 0,
  19018. /*write_timeout_sec=*/5, 0, std::string(), error);
  19019. ASSERT_NE(sock, INVALID_SOCKET);
  19020. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19021. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19022. "Host: localhost\r\n"
  19023. "Connection: close\r\n"
  19024. "\r\n";
  19025. std::string first_response;
  19026. std::string second_response;
  19027. detail::process_client_socket(
  19028. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19029. [&](Stream &strm) {
  19030. if (strm.write(req.data(), req.size()) !=
  19031. static_cast<ssize_t>(req.size())) {
  19032. return false;
  19033. }
  19034. char buf[512];
  19035. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19036. // Headers plus the two-byte body of the handler below
  19037. while (reader.getline()) {
  19038. first_response += reader.ptr();
  19039. if (first_response.find("ok") != std::string::npos) { break; }
  19040. }
  19041. if (strm.write(second.data(), second.size()) !=
  19042. static_cast<ssize_t>(second.size())) {
  19043. return true;
  19044. }
  19045. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19046. while (reader2.getline()) {
  19047. second_response += reader2.ptr();
  19048. if (second_response.find("ok") != std::string::npos) { break; }
  19049. }
  19050. return true;
  19051. });
  19052. *announced_close =
  19053. first_response.find("Connection: close") != std::string::npos;
  19054. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19055. }
  19056. class ConnectionTokenTest : public ::testing::Test {
  19057. protected:
  19058. void SetUp() override {
  19059. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19060. res.set_content("ok", "text/plain");
  19061. });
  19062. port_ = svr_.bind_to_any_port(HOST);
  19063. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19064. svr_.wait_until_ready();
  19065. }
  19066. void TearDown() override {
  19067. svr_.stop();
  19068. if (thread_.joinable()) { thread_.join(); }
  19069. }
  19070. Server svr_;
  19071. int port_ = 0;
  19072. thread thread_;
  19073. };
  19074. // "close" alongside another option still closes the connection, and the
  19075. // response says so rather than leaving the peer to discover it.
  19076. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19077. bool announced_close = false;
  19078. bool reusable = true;
  19079. probe_connection_reuse(port_,
  19080. "GET /keepalive HTTP/1.1\r\n"
  19081. "Host: localhost\r\n"
  19082. "Connection: keep-alive, close\r\n"
  19083. "\r\n",
  19084. &announced_close, &reusable);
  19085. EXPECT_TRUE(announced_close);
  19086. EXPECT_FALSE(reusable);
  19087. }
  19088. // "close" split over two field lines is the same list, so it is honored too.
  19089. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19090. bool announced_close = false;
  19091. bool reusable = true;
  19092. probe_connection_reuse(port_,
  19093. "GET /keepalive HTTP/1.1\r\n"
  19094. "Host: localhost\r\n"
  19095. "Connection: keep-alive\r\n"
  19096. "Connection: close\r\n"
  19097. "\r\n",
  19098. &announced_close, &reusable);
  19099. EXPECT_TRUE(announced_close);
  19100. EXPECT_FALSE(reusable);
  19101. }
  19102. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19103. // keep-alive in the spelling everyone actually sends keeps its connection.
  19104. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19105. bool announced_close = false;
  19106. bool reusable = false;
  19107. probe_connection_reuse(port_,
  19108. "GET /keepalive HTTP/1.0\r\n"
  19109. "Host: localhost\r\n"
  19110. "Connection: keep-alive\r\n"
  19111. "\r\n",
  19112. &announced_close, &reusable);
  19113. EXPECT_FALSE(announced_close);
  19114. EXPECT_TRUE(reusable);
  19115. }
  19116. // A token the value merely contains is not the token itself.
  19117. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19118. bool announced_close = false;
  19119. bool reusable = false;
  19120. probe_connection_reuse(port_,
  19121. "GET /keepalive HTTP/1.1\r\n"
  19122. "Host: localhost\r\n"
  19123. "Connection: notclose\r\n"
  19124. "\r\n",
  19125. &announced_close, &reusable);
  19126. EXPECT_FALSE(announced_close);
  19127. EXPECT_TRUE(reusable);
  19128. }
  19129. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19130. Server svr;
  19131. std::vector<std::string> observed_types;
  19132. svr.Get("/", [&](const Request &req, Response &res) {
  19133. observed_types = req.accept_content_types;
  19134. res.set_content("ok", "text/plain");
  19135. });
  19136. auto port = svr.bind_to_any_port(HOST);
  19137. thread t = thread([&]() { svr.listen_after_bind(); });
  19138. auto se = detail::scope_exit([&] {
  19139. svr.stop();
  19140. t.join();
  19141. ASSERT_FALSE(svr.is_running());
  19142. });
  19143. svr.wait_until_ready();
  19144. Client cli(HOST, port);
  19145. Headers headers;
  19146. headers.emplace("Accept", "text/plain;q=0.5");
  19147. headers.emplace("Accept", "application/json");
  19148. auto res = cli.Get("/", headers);
  19149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19150. EXPECT_EQ(StatusCode::OK_200, res->status);
  19151. // Sorted by q-value, so the second field line's type comes first
  19152. ASSERT_EQ(2U, observed_types.size());
  19153. EXPECT_EQ("application/json", observed_types[0]);
  19154. EXPECT_EQ("text/plain", observed_types[1]);
  19155. }
  19156. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19157. // empty field line must not contribute a bare comma to the combined value.
  19158. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19159. Server svr;
  19160. std::vector<std::string> observed_types;
  19161. svr.Get("/", [&](const Request &req, Response &res) {
  19162. observed_types = req.accept_content_types;
  19163. res.set_content("ok", "text/plain");
  19164. });
  19165. auto port = svr.bind_to_any_port(HOST);
  19166. thread t = thread([&]() { svr.listen_after_bind(); });
  19167. auto se = detail::scope_exit([&] {
  19168. svr.stop();
  19169. t.join();
  19170. ASSERT_FALSE(svr.is_running());
  19171. });
  19172. svr.wait_until_ready();
  19173. // Empty first field line, then a real one
  19174. std::string raw_req = "GET / HTTP/1.1\r\n"
  19175. "Host: localhost\r\n"
  19176. "Accept:\r\n"
  19177. "Accept: application/json\r\n"
  19178. "Connection: close\r\n"
  19179. "\r\n";
  19180. std::string out;
  19181. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19182. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19183. ASSERT_EQ(1U, observed_types.size());
  19184. EXPECT_EQ("application/json", observed_types[0]);
  19185. }
  19186. // The skip in get_combined_header_value() is what keeps an empty field line
  19187. // from contributing a bare comma. Only a trailing empty field line exercises
  19188. // it: a leading one is already covered by the "combined is still empty" check,
  19189. // and parse_accept_header() now ignores the empty element either way, so the
  19190. // request-level test above can no longer tell the two apart.
  19191. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19192. Headers headers;
  19193. headers.emplace("Accept", "text/html");
  19194. headers.emplace("Accept", "");
  19195. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19196. headers.clear();
  19197. headers.emplace("Accept", "");
  19198. headers.emplace("Accept", "application/json");
  19199. EXPECT_EQ("application/json",
  19200. detail::get_combined_header_value(headers, "Accept"));
  19201. }
  19202. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19203. // An encoding offered on a later Accept-Encoding field line is still offered.
  19204. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19205. Server svr;
  19206. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19207. res.set_content(std::string(1024, 'x'), "text/plain");
  19208. });
  19209. auto port = svr.bind_to_any_port(HOST);
  19210. thread t = thread([&]() { svr.listen_after_bind(); });
  19211. auto se = detail::scope_exit([&] {
  19212. svr.stop();
  19213. t.join();
  19214. ASSERT_FALSE(svr.is_running());
  19215. });
  19216. svr.wait_until_ready();
  19217. Client cli(HOST, port);
  19218. cli.set_decompress(false);
  19219. Headers headers;
  19220. headers.emplace("Accept-Encoding", "identity");
  19221. headers.emplace("Accept-Encoding", "gzip");
  19222. auto res = cli.Get("/", headers);
  19223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19224. EXPECT_EQ(StatusCode::OK_200, res->status);
  19225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19226. }
  19227. #endif
  19228. #ifndef _WIN32
  19229. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19230. Server svr;
  19231. svr.Post("/post", [&](const Request &req, Response &res) {
  19232. res.set_content(req.body, "text/plain");
  19233. });
  19234. svr.Put("/put", [&](const Request &req, Response &res) {
  19235. res.set_content(req.body, "text/plain");
  19236. });
  19237. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19238. res.set_content(req.body, "text/plain");
  19239. });
  19240. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19241. res.set_content(req.body, "text/plain");
  19242. });
  19243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19244. auto se = detail::scope_exit([&] {
  19245. svr.stop();
  19246. t.join();
  19247. ASSERT_FALSE(svr.is_running());
  19248. });
  19249. svr.wait_until_ready();
  19250. std::string resp;
  19251. // POST without Content-Length
  19252. ASSERT_TRUE(send_request(5,
  19253. "POST /post HTTP/1.1\r\n"
  19254. "Host: localhost\r\n"
  19255. "Connection: close\r\n"
  19256. "\r\n",
  19257. &resp));
  19258. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19259. // PUT without Content-Length
  19260. resp.clear();
  19261. ASSERT_TRUE(send_request(5,
  19262. "PUT /put HTTP/1.1\r\n"
  19263. "Host: localhost\r\n"
  19264. "Connection: close\r\n"
  19265. "\r\n",
  19266. &resp));
  19267. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19268. // PATCH without Content-Length
  19269. resp.clear();
  19270. ASSERT_TRUE(send_request(5,
  19271. "PATCH /patch HTTP/1.1\r\n"
  19272. "Host: localhost\r\n"
  19273. "Connection: close\r\n"
  19274. "\r\n",
  19275. &resp));
  19276. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19277. // DELETE without Content-Length
  19278. resp.clear();
  19279. ASSERT_TRUE(send_request(5,
  19280. "DELETE /delete HTTP/1.1\r\n"
  19281. "Host: localhost\r\n"
  19282. "Connection: close\r\n"
  19283. "\r\n",
  19284. &resp));
  19285. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19286. }
  19287. #endif
  19288. //==============================================================================
  19289. // open_stream() Tests
  19290. //==============================================================================
  19291. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19292. std::string result;
  19293. char buf[8192];
  19294. ssize_t n;
  19295. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19296. result.append(buf, static_cast<size_t>(n));
  19297. }
  19298. return result;
  19299. }
  19300. // Mock stream for unit tests
  19301. class MockStream : public Stream {
  19302. public:
  19303. std::string data;
  19304. size_t pos = 0;
  19305. ssize_t error_after = -1; // -1 = no error
  19306. explicit MockStream(const std::string &d, ssize_t err = -1)
  19307. : data(d), error_after(err) {}
  19308. bool is_readable() const override { return true; }
  19309. bool wait_readable() const override { return true; }
  19310. bool wait_writable() const override { return true; }
  19311. ssize_t read(char *ptr, size_t size) override {
  19312. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19313. if (pos >= data.size()) return 0;
  19314. size_t limit =
  19315. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19316. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19317. std::memcpy(ptr, data.data() + pos, to_read);
  19318. pos += to_read;
  19319. return static_cast<ssize_t>(to_read);
  19320. }
  19321. ssize_t write(const char *, size_t) override { return -1; }
  19322. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19323. ip = "127.0.0.1";
  19324. port = 0;
  19325. }
  19326. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19327. ip = "127.0.0.1";
  19328. port = 0;
  19329. }
  19330. socket_t socket() const override { return INVALID_SOCKET; }
  19331. time_t duration() const override { return 0; }
  19332. };
  19333. TEST(StreamHandleTest, Basic) {
  19334. ClientImpl::StreamHandle handle;
  19335. EXPECT_FALSE(handle.is_valid());
  19336. handle.response = detail::make_unique<Response>();
  19337. handle.error = Error::Connection;
  19338. EXPECT_FALSE(handle.is_valid());
  19339. handle.error = Error::Success;
  19340. EXPECT_TRUE(handle.is_valid());
  19341. }
  19342. TEST(BodyReaderTest, Basic) {
  19343. MockStream stream("Hello, World!");
  19344. detail::BodyReader reader;
  19345. reader.stream = &stream;
  19346. reader.content_length = 13;
  19347. char buf[32];
  19348. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19349. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19350. EXPECT_TRUE(reader.eof);
  19351. }
  19352. TEST(BodyReaderTest, NoStream) {
  19353. detail::BodyReader reader;
  19354. char buf[32];
  19355. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19356. EXPECT_EQ(Error::Connection, reader.last_error);
  19357. }
  19358. TEST(BodyReaderTest, Error) {
  19359. MockStream stream("Hello, World!", 5);
  19360. detail::BodyReader reader;
  19361. reader.stream = &stream;
  19362. reader.content_length = 13;
  19363. char buf[32];
  19364. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19366. EXPECT_EQ(Error::Read, reader.last_error);
  19367. }
  19368. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19369. // Mock-based StreamHandle tests relying on private internals are removed.
  19370. class OpenStreamTest : public ::testing::Test {
  19371. protected:
  19372. void SetUp() override {
  19373. svr_.Get("/hello", [](const Request &, Response &res) {
  19374. res.set_content("Hello World!", "text/plain");
  19375. });
  19376. svr_.Get("/large", [](const Request &, Response &res) {
  19377. res.set_content(std::string(10000, 'X'), "text/plain");
  19378. });
  19379. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19380. res.set_content("Hello World!", "image/jpeg");
  19381. res.set_header("Content-Encoding", "UTF-8");
  19382. });
  19383. svr_.Get("/chunked", [](const Request &, Response &res) {
  19384. res.set_chunked_content_provider("text/plain",
  19385. [](size_t offset, DataSink &sink) {
  19386. if (offset < 15) {
  19387. sink.write("chunk", 5);
  19388. return true;
  19389. }
  19390. sink.done();
  19391. return true;
  19392. });
  19393. });
  19394. svr_.Get("/compressible", [](const Request &, Response &res) {
  19395. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19396. DataSink &sink) {
  19397. if (offset < 100 * 1024) {
  19398. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19399. sink.write(chunk.data(), chunk.size());
  19400. return true;
  19401. }
  19402. sink.done();
  19403. return true;
  19404. });
  19405. });
  19406. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19407. [](const Request & /*req*/, Response &res) {
  19408. auto i = new int(0);
  19409. res.set_header("Trailer", "Content-Length, X-Allowed");
  19410. res.set_chunked_content_provider(
  19411. "text/plain",
  19412. [i](size_t /*offset*/, DataSink &sink) {
  19413. switch (*i) {
  19414. case 0: sink.os << "123"; break;
  19415. case 1: sink.os << "456"; break;
  19416. case 2: sink.os << "789"; break;
  19417. case 3: {
  19418. sink.done_with_trailer(
  19419. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19420. } break;
  19421. }
  19422. (*i)++;
  19423. return true;
  19424. },
  19425. [i](bool success) {
  19426. EXPECT_TRUE(success);
  19427. delete i;
  19428. });
  19429. });
  19430. // Echo headers endpoint for header-related tests
  19431. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19432. std::string body;
  19433. for (const auto &h : req.headers) {
  19434. body.append(h.first);
  19435. body.push_back(':');
  19436. body.append(h.second);
  19437. body.push_back('\n');
  19438. }
  19439. res.set_content(body, "text/plain");
  19440. });
  19441. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19442. std::string body;
  19443. for (const auto &h : req.headers) {
  19444. body.append(h.first);
  19445. body.push_back(':');
  19446. body.append(h.second);
  19447. body.push_back('\n');
  19448. }
  19449. res.set_content(body, "text/plain");
  19450. });
  19451. port_ = svr_.bind_to_any_port("127.0.0.1");
  19452. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19453. svr_.wait_until_ready();
  19454. }
  19455. void TearDown() override {
  19456. svr_.stop();
  19457. if (thread_.joinable()) thread_.join();
  19458. }
  19459. Server svr_;
  19460. std::thread thread_;
  19461. int port_ = 0;
  19462. };
  19463. TEST_F(OpenStreamTest, Basic) {
  19464. Client cli("127.0.0.1", port_);
  19465. auto handle = cli.open_stream("GET", "/hello");
  19466. EXPECT_TRUE(handle.is_valid());
  19467. EXPECT_EQ("Hello World!", read_all(handle));
  19468. }
  19469. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19470. Client cli("127.0.0.1", port_);
  19471. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19472. ASSERT_TRUE(handle.is_valid());
  19473. EXPECT_EQ("Hello World!", read_all(handle));
  19474. }
  19475. TEST_F(OpenStreamTest, SmallBuffer) {
  19476. Client cli("127.0.0.1", port_);
  19477. auto handle = cli.open_stream("GET", "/hello");
  19478. std::string result;
  19479. char buf[4];
  19480. ssize_t n;
  19481. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19482. result.append(buf, static_cast<size_t>(n));
  19483. EXPECT_EQ("Hello World!", result);
  19484. }
  19485. TEST_F(OpenStreamTest, DefaultHeaders) {
  19486. Client cli("127.0.0.1", port_);
  19487. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19488. {
  19489. auto handle = cli.open_stream("GET", "/echo-headers");
  19490. ASSERT_TRUE(handle.is_valid());
  19491. auto body = read_all(handle);
  19492. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19493. std::string::npos);
  19494. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19495. std::string::npos);
  19496. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19497. }
  19498. // open_stream POST with body and no explicit content_type should NOT add
  19499. // text/plain Content-Type (behavior differs from non-streaming path), but
  19500. // should include Content-Length
  19501. {
  19502. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19503. ASSERT_TRUE(handle.is_valid());
  19504. auto body = read_all(handle);
  19505. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19506. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19507. }
  19508. // open_stream POST with explicit Content-Type should preserve it
  19509. {
  19510. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19511. {{"Content-Type", "application/custom"}},
  19512. "{}", "application/custom");
  19513. ASSERT_TRUE(handle.is_valid());
  19514. auto body = read_all(handle);
  19515. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19516. }
  19517. // User-specified User-Agent must not be overwritten for stream API
  19518. {
  19519. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19520. {{"User-Agent", "MyAgent/1.2"}});
  19521. ASSERT_TRUE(handle.is_valid());
  19522. auto body = read_all(handle);
  19523. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19524. }
  19525. }
  19526. TEST_F(OpenStreamTest, Large) {
  19527. Client cli("127.0.0.1", port_);
  19528. auto handle = cli.open_stream("GET", "/large");
  19529. EXPECT_EQ(10000u, read_all(handle).size());
  19530. }
  19531. TEST_F(OpenStreamTest, ConnectionError) {
  19532. Client cli("127.0.0.1", 9999);
  19533. auto handle = cli.open_stream("GET", "/hello");
  19534. EXPECT_FALSE(handle.is_valid());
  19535. }
  19536. TEST_F(OpenStreamTest, Chunked) {
  19537. Client cli("127.0.0.1", port_);
  19538. auto handle = cli.open_stream("GET", "/chunked");
  19539. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19540. "Transfer-Encoding") == "chunked");
  19541. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19542. }
  19543. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19544. Client cli("127.0.0.1", port_);
  19545. auto handle =
  19546. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19547. ASSERT_TRUE(handle.is_valid());
  19548. // Consume body to allow trailers to be received/parsed
  19549. auto body = read_all(handle);
  19550. // Explicitly parse trailers (ensure trailers are available for assertion)
  19551. handle.parse_trailers_if_needed();
  19552. EXPECT_EQ(std::string("123456789"), body);
  19553. // The response should include a Trailer header declaring both names
  19554. ASSERT_TRUE(handle.response);
  19555. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19556. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19557. handle.response->get_header_value("Trailer"));
  19558. // Prohibited trailer must not be present
  19559. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19560. // Allowed trailer should be present
  19561. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19562. EXPECT_EQ(std::string("yes"),
  19563. handle.response->get_trailer_value("X-Allowed"));
  19564. // Verify trailers are NOT present as regular headers
  19565. EXPECT_EQ(std::string(""),
  19566. handle.response->get_header_value("Content-Length"));
  19567. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19568. }
  19569. // Accepts one connection on an OS-assigned port, which it hands over through
  19570. // port_promise, reads the request head and sends back response. after_send,
  19571. // if given, runs on the connection before it is closed.
  19572. static std::thread
  19573. serve_single_response(std::promise<int> &port_promise,
  19574. const std::string &response,
  19575. std::function<void(socket_t)> after_send = nullptr) {
  19576. return std::thread([&port_promise, response, after_send] {
  19577. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19578. default_socket_options(srv);
  19579. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19581. sockaddr_in addr{};
  19582. addr.sin_family = AF_INET;
  19583. addr.sin_port = htons(0); // Let OS assign a free port
  19584. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19585. int opt = 1;
  19586. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19587. #ifdef _WIN32
  19588. reinterpret_cast<const char *>(&opt),
  19589. #else
  19590. &opt,
  19591. #endif
  19592. sizeof(opt));
  19593. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19594. ::listen(srv, 1) != 0) {
  19595. port_promise.set_value(-1);
  19596. detail::close_socket(srv);
  19597. return;
  19598. }
  19599. socklen_t addr_len = sizeof(addr);
  19600. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19601. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19602. sockaddr_in cli_addr{};
  19603. socklen_t cli_len = sizeof(cli_addr);
  19604. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19605. if (cli != INVALID_SOCKET) {
  19606. // Read the complete HTTP request (until the blank line that terminates
  19607. // headers) before sending the response. If the server closes the socket
  19608. // while the client's request data is still unread in the kernel receive
  19609. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19610. // connection on both sides: it discards the client's receive buffer
  19611. // (which already holds our response) and causes any in-progress write on
  19612. // the client to fail with ECONNRESET. Reading all request data first
  19613. // ensures close() emits a graceful FIN.
  19614. {
  19615. char rbuf[256];
  19616. std::string req;
  19617. while (req.find("\r\n\r\n") == std::string::npos) {
  19618. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19619. if (n <= 0) { break; }
  19620. req.append(rbuf, static_cast<size_t>(n));
  19621. }
  19622. }
  19623. ::send(cli,
  19624. #ifdef _WIN32
  19625. static_cast<const char *>(response.c_str()),
  19626. static_cast<int>(response.size()),
  19627. #else
  19628. response.c_str(), response.size(),
  19629. #endif
  19630. 0);
  19631. if (after_send) { after_send(cli); }
  19632. detail::close_socket(cli);
  19633. }
  19634. detail::close_socket(srv);
  19635. });
  19636. }
  19637. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19638. #ifndef _WIN32
  19639. signal(SIGPIPE, SIG_IGN);
  19640. #endif
  19641. std::promise<int> port_promise;
  19642. auto port_future = port_promise.get_future();
  19643. auto server_thread =
  19644. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19645. "Content-Type: text/plain\r\n"
  19646. "Content-Length: not-a-number\r\n"
  19647. "Connection: close\r\n"
  19648. "\r\n"
  19649. "hello");
  19650. auto port = port_future.get();
  19651. ASSERT_GT(port, 0);
  19652. Client cli("127.0.0.1", port);
  19653. auto handle = cli.open_stream("GET", "/");
  19654. EXPECT_FALSE(handle.is_valid());
  19655. server_thread.join();
  19656. }
  19657. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19658. #ifndef _WIN32
  19659. signal(SIGPIPE, SIG_IGN);
  19660. #endif
  19661. std::promise<int> port_promise;
  19662. auto port_future = port_promise.get_future();
  19663. auto server_thread = serve_single_response(
  19664. port_promise, "HTTP/1.1 200 OK\r\n"
  19665. "Content-Type: text/plain\r\n"
  19666. "Content-Length: 99999999999999999999999999\r\n"
  19667. "Connection: close\r\n"
  19668. "\r\n"
  19669. "hello");
  19670. auto port = port_future.get();
  19671. ASSERT_GT(port, 0);
  19672. // Historically std::stoull would throw std::out_of_range here and crash
  19673. // the process, then parsing silently clamped to a bogus framing length and
  19674. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19675. // so the stream fails to open, matching the not-a-number case above. The
  19676. // process still must NOT terminate.
  19677. Client cli("127.0.0.1", port);
  19678. auto handle = cli.open_stream("GET", "/");
  19679. EXPECT_FALSE(handle.is_valid());
  19680. server_thread.join();
  19681. }
  19682. // Serves `response` to the single request `fn` makes with a fresh client.
  19683. template <typename Fn>
  19684. static void with_single_response(const std::string &response, Fn fn) {
  19685. #ifndef _WIN32
  19686. signal(SIGPIPE, SIG_IGN);
  19687. #endif
  19688. std::promise<int> port_promise;
  19689. auto port_future = port_promise.get_future();
  19690. auto server_thread = serve_single_response(port_promise, response);
  19691. auto se = detail::scope_exit([&] { server_thread.join(); });
  19692. auto port = port_future.get();
  19693. ASSERT_GT(port, 0);
  19694. Client cli("127.0.0.1", port);
  19695. fn(cli);
  19696. }
  19697. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19698. // Neither Content-Length nor chunked: the body ends at the close
  19699. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19700. "Connection: close\r\n"
  19701. "\r\n"
  19702. "hello";
  19703. with_single_response(close_delimited, [](Client &cli) {
  19704. auto handle = cli.open_stream("GET", "/");
  19705. ASSERT_TRUE(handle.is_valid());
  19706. EXPECT_EQ("hello", read_all(handle));
  19707. EXPECT_FALSE(handle.has_read_error());
  19708. });
  19709. // A close before the end of the Content-Length is still an error
  19710. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19711. "Content-Length: 10\r\n"
  19712. "\r\n"
  19713. "hello";
  19714. with_single_response(short_content_length, [](Client &cli) {
  19715. auto handle = cli.open_stream("GET", "/");
  19716. ASSERT_TRUE(handle.is_valid());
  19717. read_all(handle);
  19718. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19719. });
  19720. // So is a close before the last chunk
  19721. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19722. "Transfer-Encoding: chunked\r\n"
  19723. "\r\n"
  19724. "5\r\nhello\r\n";
  19725. with_single_response(short_chunked, [](Client &cli) {
  19726. auto handle = cli.open_stream("GET", "/");
  19727. ASSERT_TRUE(handle.is_valid());
  19728. read_all(handle);
  19729. EXPECT_TRUE(handle.has_read_error());
  19730. });
  19731. }
  19732. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19733. const char *responses[] = {
  19734. "HTTP/1.1 103 Early Hints\r\n"
  19735. "Link: </style.css>; rel=preload\r\n"
  19736. "\r\n"
  19737. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19738. "HTTP/1.1 100 Continue\r\n"
  19739. "X-Note: interim\r\n"
  19740. "\r\n"
  19741. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19742. };
  19743. for (auto response : responses) {
  19744. with_single_response(response, [](Client &cli) {
  19745. auto res = cli.Get("/");
  19746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19747. EXPECT_EQ(StatusCode::OK_200, res->status);
  19748. EXPECT_EQ("ok", res->body);
  19749. });
  19750. }
  19751. }
  19752. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19753. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19754. const std::string final_response =
  19755. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19756. std::string interims;
  19757. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19758. interims += interim;
  19759. }
  19760. with_single_response(interims + final_response, [](Client &cli) {
  19761. auto res = cli.Get("/");
  19762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19763. EXPECT_EQ("ok", res->body);
  19764. });
  19765. with_single_response(interims + interim + final_response, [](Client &cli) {
  19766. auto res = cli.Get("/");
  19767. ASSERT_FALSE(res);
  19768. EXPECT_EQ(Error::Read, res.error());
  19769. });
  19770. }
  19771. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19772. #ifndef _WIN32
  19773. signal(SIGPIPE, SIG_IGN);
  19774. #endif
  19775. // The server answers the head without asking for the body. Bytes it then
  19776. // reads on the connection would be taken for the body the request declared.
  19777. auto closed_by_client = false;
  19778. std::promise<int> port_promise;
  19779. auto server_thread = serve_single_response(
  19780. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19781. [&](socket_t sock) {
  19782. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19783. char buf[256];
  19784. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19785. });
  19786. Client cli("127.0.0.1", port_promise.get_future().get());
  19787. cli.set_keep_alive(true);
  19788. cli.set_read_timeout(1, 0);
  19789. // Long enough for the client to send Expect: 100-continue.
  19790. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19792. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19793. cli.Get("/second");
  19794. server_thread.join();
  19795. EXPECT_TRUE(closed_by_client);
  19796. }
  19797. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19798. // Long enough for the client to send Expect: 100-continue
  19799. with_single_response(
  19800. "HTTP/1.1 103 Early Hints\r\n"
  19801. "Link: </style.css>; rel=preload\r\n"
  19802. "\r\n"
  19803. "HTTP/1.1 401 Unauthorized\r\n"
  19804. "Content-Length: 0\r\n\r\n",
  19805. [](Client &cli) {
  19806. cli.set_read_timeout(2, 0);
  19807. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19810. });
  19811. }
  19812. #ifdef CPPHTTPLIB_SSL_ENABLED
  19813. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19814. #ifndef _WIN32
  19815. signal(SIGPIPE, SIG_IGN);
  19816. #endif
  19817. auto reused = false;
  19818. std::promise<int> port_promise;
  19819. auto server_thread = serve_single_response(
  19820. port_promise,
  19821. "HTTP/1.1 401 Unauthorized\r\n"
  19822. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19823. "Content-Length: 0\r\n\r\n",
  19824. [&](socket_t sock) {
  19825. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19826. char buf[256];
  19827. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19828. });
  19829. Client cli("127.0.0.1", port_promise.get_future().get());
  19830. cli.set_keep_alive(true);
  19831. cli.set_digest_auth("user", "pass");
  19832. cli.set_read_timeout(1, 0);
  19833. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19834. server_thread.join();
  19835. EXPECT_FALSE(reused);
  19836. }
  19837. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19838. // Any other answer to CONNECT would read as the origin's response.
  19839. struct {
  19840. const char *response;
  19841. bool passed_on;
  19842. } cases[] = {
  19843. {"HTTP/1.1 201 Created\r\n"
  19844. "Set-Cookie: session=from-proxy\r\n"
  19845. "Content-Length: 0\r\n\r\n",
  19846. false},
  19847. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19848. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19849. "Content-Length: 0\r\n\r\n",
  19850. true},
  19851. };
  19852. for (const auto &c : cases) {
  19853. std::promise<int> port_promise;
  19854. auto server_thread = serve_single_response(port_promise, c.response);
  19855. SSLClient cli("example.com", 443);
  19856. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19857. auto res = cli.Get("/");
  19858. server_thread.join();
  19859. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19860. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19861. if (res) {
  19862. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19863. }
  19864. }
  19865. }
  19866. #endif
  19867. // Records the client's error logger calls as "error METHOD path", or
  19868. // "error null" for a call without a request
  19869. static ErrorLogger record_errors(std::vector<std::string> &log) {
  19870. return [&log](const Error &err, const Request *req) {
  19871. log.push_back(to_string(err) + " " +
  19872. (req ? req->method + " " + req->path : "null"));
  19873. };
  19874. }
  19875. // A failed request is reported once, with the request the caller made
  19876. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  19877. Server svr;
  19878. svr.Get("/big", [](const Request &, Response &res) {
  19879. res.set_content(std::string(100000, 'b'), "text/plain");
  19880. });
  19881. auto port = svr.bind_to_any_port(HOST);
  19882. std::thread t([&]() { svr.listen_after_bind(); });
  19883. auto se = detail::scope_exit([&] {
  19884. svr.stop();
  19885. t.join();
  19886. });
  19887. svr.wait_until_ready();
  19888. Client cli(HOST, port);
  19889. std::vector<std::string> log;
  19890. cli.set_error_logger(record_errors(log));
  19891. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  19892. cli.Get("/big", [](const char *, size_t) { return false; });
  19893. EXPECT_EQ(expected, log);
  19894. log.clear();
  19895. cli.Get("/big", [](size_t, size_t) { return false; });
  19896. EXPECT_EQ(expected, log);
  19897. }
  19898. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  19899. // Fails while the body is read
  19900. auto broken = [](const Request &, Response &res) {
  19901. res.set_content_provider(10, "text/plain",
  19902. [](size_t, size_t, DataSink &) { return false; });
  19903. };
  19904. Server other;
  19905. other.Get("/broken", broken);
  19906. auto other_port = other.bind_to_any_port(HOST);
  19907. std::thread other_t([&]() { other.listen_after_bind(); });
  19908. auto other_se = detail::scope_exit([&] {
  19909. other.stop();
  19910. other_t.join();
  19911. });
  19912. other.wait_until_ready();
  19913. Server svr;
  19914. svr.Get("/broken", broken);
  19915. svr.Get("/same-origin",
  19916. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  19917. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  19918. res.set_redirect("http://" + std::string(HOST) + ":" +
  19919. std::to_string(other_port) + "/broken");
  19920. });
  19921. auto port = svr.bind_to_any_port(HOST);
  19922. std::thread t([&]() { svr.listen_after_bind(); });
  19923. auto se = detail::scope_exit([&] {
  19924. svr.stop();
  19925. t.join();
  19926. });
  19927. svr.wait_until_ready();
  19928. Client cli(HOST, port);
  19929. cli.set_follow_location(true);
  19930. std::vector<std::string> log;
  19931. cli.set_error_logger(record_errors(log));
  19932. for (auto path : {"/same-origin", "/cross-origin"}) {
  19933. log.clear();
  19934. auto res = cli.Get(path);
  19935. ASSERT_FALSE(res);
  19936. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  19937. log);
  19938. }
  19939. }
  19940. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  19941. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  19942. std::vector<std::string> log;
  19943. cli.set_error_logger(record_errors(log));
  19944. auto handle = cli.open_stream("GET", "/x");
  19945. EXPECT_FALSE(handle.is_valid());
  19946. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  19947. log);
  19948. });
  19949. }
  19950. #ifdef CPPHTTPLIB_SSL_ENABLED
  19951. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  19952. // Not a TLS server, so the handshake fails. It waits for a request line in
  19953. // the handshake bytes, so a short read timeout lets it close quickly.
  19954. Server svr;
  19955. svr.set_read_timeout(0, 100000);
  19956. svr.Get("/x", [](const Request &, Response &res) {
  19957. res.set_content("x", "text/plain");
  19958. });
  19959. auto port = svr.bind_to_any_port(HOST);
  19960. std::thread t([&]() { svr.listen_after_bind(); });
  19961. auto se = detail::scope_exit([&] {
  19962. svr.stop();
  19963. t.join();
  19964. });
  19965. svr.wait_until_ready();
  19966. std::vector<std::string> log;
  19967. SSLClient cli(HOST, port);
  19968. cli.enable_server_certificate_verification(false);
  19969. cli.set_error_logger(record_errors(log));
  19970. auto res = cli.Get("/x");
  19971. ASSERT_FALSE(res);
  19972. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  19973. log.clear();
  19974. auto handle = cli.open_stream("GET", "/x");
  19975. EXPECT_FALSE(handle.is_valid());
  19976. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  19977. log.clear();
  19978. SSLClient no_ca(HOST, port);
  19979. no_ca.set_ca_cert_path("./no-such-ca.pem");
  19980. no_ca.set_error_logger(record_errors(log));
  19981. res = no_ca.Get("/x");
  19982. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  19983. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  19984. }
  19985. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  19986. #ifndef _WIN32
  19987. signal(SIGPIPE, SIG_IGN);
  19988. #endif
  19989. // Refused, answered with a challenge, or closed without an answer
  19990. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  19991. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  19992. "Content-Length: 0\r\n\r\n",
  19993. ""}) {
  19994. std::promise<int> port_promise;
  19995. auto server_thread = serve_single_response(port_promise, response);
  19996. SSLClient cli("example.com", 443);
  19997. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19998. std::vector<std::string> log;
  19999. cli.set_error_logger(record_errors(log));
  20000. auto res = cli.Get("/");
  20001. server_thread.join();
  20002. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20003. << response;
  20004. }
  20005. }
  20006. #endif
  20007. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20008. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20009. // the chunked coding and drop Content-Length, so a front-end that trusts
  20010. // Content-Length would disagree about where the body ends (response
  20011. // smuggling). The client must reject such a response.
  20012. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20013. for (const char *te : {"chunked", "gzip, chunked"}) {
  20014. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20015. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20016. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20017. "5\r\nhello\r\n0\r\n\r\n";
  20018. with_single_response(response, [&](Client &cli) {
  20019. auto res = cli.Get("/");
  20020. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20021. EXPECT_EQ(Error::Read, res.error()) << te;
  20022. });
  20023. with_single_response(response, [&](Client &cli) {
  20024. auto handle = cli.open_stream("GET", "/");
  20025. EXPECT_FALSE(handle.is_valid()) << te;
  20026. EXPECT_EQ(Error::Read, handle.error) << te;
  20027. });
  20028. }
  20029. }
  20030. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20031. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20032. // closing the connection (unlike a request, which must be rejected).
  20033. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20034. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20035. "Transfer-Encoding: chunked\r\n"
  20036. "Connection: close\r\n"
  20037. "\r\n"
  20038. "5\r\nhello\r\n0\r\n\r\n",
  20039. "HTTP/1.1 200 OK\r\n"
  20040. "Transfer-Encoding: gzip\r\n"
  20041. "Connection: close\r\n"
  20042. "\r\n"
  20043. "hello"}) {
  20044. with_single_response(response, [&](Client &cli) {
  20045. auto res = cli.Get("/");
  20046. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20047. EXPECT_EQ("hello", res->body);
  20048. });
  20049. with_single_response(response, [&](Client &cli) {
  20050. auto handle = cli.open_stream("GET", "/");
  20051. ASSERT_TRUE(handle.is_valid()) << response;
  20052. EXPECT_EQ("hello", read_all(handle));
  20053. });
  20054. }
  20055. }
  20056. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20057. // framing headers describe nothing to read and must not be rejected.
  20058. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20059. const std::string framing = "Content-Length: 5\r\n"
  20060. "Transfer-Encoding: chunked\r\n"
  20061. "Connection: close\r\n"
  20062. "\r\n";
  20063. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20064. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20065. });
  20066. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20067. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20068. });
  20069. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20070. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20071. with_single_response(response, [&](Client &cli) {
  20072. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20073. });
  20074. with_single_response(response, [&](Client &cli) {
  20075. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20076. });
  20077. }
  20078. }
  20079. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20080. // header section, so a stream opened on one has nothing to read, whatever
  20081. // framing or coding headers it carries.
  20082. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20083. struct Case {
  20084. const char *method;
  20085. const char *status;
  20086. };
  20087. // A reader of the declared body reports an early close when nothing
  20088. // follows, and hands back what does.
  20089. struct Framing {
  20090. const char *headers;
  20091. const char *after;
  20092. };
  20093. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20094. Case{"GET", "304 Not Modified"}}) {
  20095. for (const auto &f :
  20096. {Framing{"Content-Length: 5\r\n", ""},
  20097. Framing{"Content-Length: 5\r\n", "hello"},
  20098. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20099. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20100. // Not decoded, so a build without Brotli opens it too
  20101. Framing{"Content-Encoding: br\r\n", ""}}) {
  20102. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20103. "Connection: close\r\n"
  20104. "\r\n" +
  20105. f.after;
  20106. with_single_response(response, [&](Client &cli) {
  20107. auto handle = cli.open_stream(c.method, "/");
  20108. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20109. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20110. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20111. });
  20112. }
  20113. }
  20114. }
  20115. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20116. // response, is faulty framing, so the connection is not reused after it.
  20117. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20118. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20119. "Content-Length: 0\r\n"
  20120. "Transfer-Encoding: chunked\r\n"
  20121. "\r\n"
  20122. "5\r\nhello\r\n0\r\n\r\n",
  20123. "HTTP/1.0 200 Connection established\r\n"
  20124. "Connection: keep-alive\r\n"
  20125. "Transfer-Encoding: chunked\r\n"
  20126. "\r\n"
  20127. "5\r\nhello\r\n0\r\n\r\n"}) {
  20128. with_single_response(response, [&](Client &cli) {
  20129. cli.set_keep_alive(true);
  20130. auto res = cli.Get("/");
  20131. ASSERT_TRUE(res) << response;
  20132. EXPECT_EQ("hello", res->body);
  20133. EXPECT_FALSE(cli.is_socket_open()) << response;
  20134. });
  20135. }
  20136. }
  20137. // A payload max length of 0 means no limit, however the body is framed.
  20138. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20139. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20140. "Transfer-Encoding: chunked\r\n"
  20141. "\r\n"
  20142. "5\r\nhello\r\n0\r\n\r\n",
  20143. "HTTP/1.1 200 OK\r\n"
  20144. "Connection: close\r\n"
  20145. "\r\n"
  20146. "hello"}) {
  20147. with_single_response(response, [&](Client &cli) {
  20148. cli.set_payload_max_length(0);
  20149. auto res = cli.Get("/");
  20150. ASSERT_TRUE(res) << response;
  20151. EXPECT_EQ("hello", res->body) << response;
  20152. });
  20153. }
  20154. }
  20155. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20156. Server svr;
  20157. svr.set_payload_max_length(0);
  20158. svr.Post("/echo", [](const Request &req, Response &res) {
  20159. res.set_content(req.body, "text/plain");
  20160. });
  20161. auto port = svr.bind_to_any_port(HOST);
  20162. thread t = thread([&] { svr.listen_after_bind(); });
  20163. auto se = detail::scope_exit([&] {
  20164. svr.stop();
  20165. t.join();
  20166. ASSERT_FALSE(svr.is_running());
  20167. });
  20168. svr.wait_until_ready();
  20169. Client cli(HOST, port);
  20170. auto res = cli.Post(
  20171. "/echo",
  20172. [](size_t /*offset*/, DataSink &sink) {
  20173. sink.write("hello", 5);
  20174. sink.done();
  20175. return true;
  20176. },
  20177. "text/plain");
  20178. ASSERT_TRUE(res);
  20179. EXPECT_EQ(StatusCode::OK_200, res->status);
  20180. EXPECT_EQ("hello", res->body);
  20181. }
  20182. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20183. TEST_F(OpenStreamTest, Gzip) {
  20184. Client cli("127.0.0.1", port_);
  20185. auto handle = cli.open_stream("GET", "/compressible", {},
  20186. {{"Accept-Encoding", "gzip"}});
  20187. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20188. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20189. }
  20190. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20191. Client cli("127.0.0.1", port_);
  20192. auto handle =
  20193. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20194. {{"Accept-Encoding", "gzip"}});
  20195. ASSERT_TRUE(handle.is_valid());
  20196. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20197. EXPECT_EQ("123456789", read_all(handle));
  20198. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20199. }
  20200. #endif
  20201. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20202. TEST_F(OpenStreamTest, Brotli) {
  20203. Client cli("127.0.0.1", port_);
  20204. auto handle =
  20205. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20206. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20207. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20208. }
  20209. #endif
  20210. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20211. TEST_F(OpenStreamTest, Zstd) {
  20212. Client cli("127.0.0.1", port_);
  20213. auto handle = cli.open_stream("GET", "/compressible", {},
  20214. {{"Accept-Encoding", "zstd"}});
  20215. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20216. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20217. }
  20218. #endif
  20219. #ifdef CPPHTTPLIB_SSL_ENABLED
  20220. class SSLOpenStreamTest : public ::testing::Test {
  20221. protected:
  20222. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20223. void SetUp() override {
  20224. svr_.Get("/hello", [](const Request &, Response &res) {
  20225. res.set_content("Hello SSL World!", "text/plain");
  20226. });
  20227. svr_.Get("/chunked", [](const Request &, Response &res) {
  20228. res.set_chunked_content_provider("text/plain",
  20229. [](size_t offset, DataSink &sink) {
  20230. if (offset < 15) {
  20231. sink.write("chunk", 5);
  20232. return true;
  20233. }
  20234. sink.done();
  20235. return true;
  20236. });
  20237. });
  20238. svr_.Post("/echo", [](const Request &req, Response &res) {
  20239. res.set_content(req.body, req.get_header_value("Content-Type"));
  20240. });
  20241. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20242. std::string body = req.body;
  20243. res.set_chunked_content_provider(
  20244. "text/plain", [body](size_t offset, DataSink &sink) {
  20245. if (offset < body.size()) {
  20246. sink.write(body.data() + offset, body.size() - offset);
  20247. }
  20248. sink.done();
  20249. return true;
  20250. });
  20251. });
  20252. port_ = svr_.bind_to_any_port("127.0.0.1");
  20253. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20254. svr_.wait_until_ready();
  20255. }
  20256. void TearDown() override {
  20257. svr_.stop();
  20258. if (thread_.joinable()) thread_.join();
  20259. }
  20260. SSLServer svr_;
  20261. std::thread thread_;
  20262. int port_ = 0;
  20263. };
  20264. TEST_F(SSLOpenStreamTest, Basic) {
  20265. SSLClient cli("127.0.0.1", port_);
  20266. cli.enable_server_certificate_verification(false);
  20267. auto handle = cli.open_stream("GET", "/hello");
  20268. ASSERT_TRUE(handle.is_valid());
  20269. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20270. }
  20271. TEST_F(SSLOpenStreamTest, Chunked) {
  20272. SSLClient cli("127.0.0.1", port_);
  20273. cli.enable_server_certificate_verification(false);
  20274. auto handle = cli.open_stream("GET", "/chunked");
  20275. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20276. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20277. "Transfer-Encoding") == "chunked");
  20278. auto body = read_all(handle);
  20279. EXPECT_EQ("chunkchunkchunk", body);
  20280. }
  20281. TEST_F(SSLOpenStreamTest, Post) {
  20282. SSLClient cli("127.0.0.1", port_);
  20283. cli.enable_server_certificate_verification(false);
  20284. auto handle =
  20285. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20286. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20287. EXPECT_EQ(200, handle.response->status);
  20288. auto body = read_all(handle);
  20289. EXPECT_EQ("Hello SSL POST", body);
  20290. }
  20291. TEST_F(SSLOpenStreamTest, PostChunked) {
  20292. SSLClient cli("127.0.0.1", port_);
  20293. cli.enable_server_certificate_verification(false);
  20294. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20295. "Chunked SSL Data", "text/plain");
  20296. ASSERT_TRUE(handle.is_valid());
  20297. EXPECT_EQ(200, handle.response->status);
  20298. auto body = read_all(handle);
  20299. EXPECT_EQ("Chunked SSL Data", body);
  20300. }
  20301. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20302. // Content-Length is terminated by the server closing the connection. When the
  20303. // SSL peer sends a close_notify after the body, the client must treat it as a
  20304. // clean EOF and return a successful response rather than an error.
  20305. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20307. ASSERT_TRUE(svr.is_valid());
  20308. svr.set_keep_alive_max_count(1);
  20309. const std::string expected_body = "Hello from connection-close response!";
  20310. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20311. res.set_content_provider("text/plain",
  20312. [&](size_t offset, DataSink &sink) -> bool {
  20313. if (offset < expected_body.size()) {
  20314. sink.write(expected_body.data() + offset,
  20315. expected_body.size() - offset);
  20316. }
  20317. sink.done();
  20318. return true;
  20319. });
  20320. });
  20321. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20322. auto se = detail::scope_exit([&] {
  20323. svr.stop();
  20324. listen_thread.join();
  20325. ASSERT_FALSE(svr.is_running());
  20326. });
  20327. svr.wait_until_ready();
  20328. SSLClient cli(HOST, PORT);
  20329. cli.enable_server_certificate_verification(false);
  20330. auto res = cli.Get("/no-content-length");
  20331. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20332. EXPECT_EQ(StatusCode::OK_200, res->status);
  20333. EXPECT_EQ(expected_body, res->body);
  20334. }
  20335. #endif // CPPHTTPLIB_SSL_ENABLED
  20336. //==============================================================================
  20337. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20338. // results for various scenarios.
  20339. //==============================================================================
  20340. TEST(ParityTest, GetVsOpenStream) {
  20341. Server svr;
  20342. const std::string path = "/parity";
  20343. const std::string content = "Parity test content: hello world";
  20344. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20345. res.set_content(content, "text/plain");
  20346. });
  20347. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20348. auto se = detail::scope_exit([&] {
  20349. svr.stop();
  20350. t.join();
  20351. ASSERT_FALSE(svr.is_running());
  20352. });
  20353. svr.wait_until_ready();
  20354. Client cli(HOST, PORT);
  20355. // Non-stream path
  20356. auto r1 = cli.Get(path);
  20357. ASSERT_TRUE(r1);
  20358. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20359. // Stream path
  20360. auto h = cli.open_stream("GET", path);
  20361. ASSERT_TRUE(h.is_valid());
  20362. EXPECT_EQ(r1->body, read_all(h));
  20363. }
  20364. // Helper to compress data with provided compressor type T
  20365. template <typename Compressor>
  20366. static std::string compress_payload_for_parity(const std::string &in) {
  20367. std::string out;
  20368. Compressor compressor;
  20369. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20370. [&](const char *data, size_t n) {
  20371. out.append(data, n);
  20372. return true;
  20373. });
  20374. EXPECT_TRUE(ok);
  20375. return out;
  20376. }
  20377. // Helper function for compression parity tests
  20378. template <typename Compressor>
  20379. static void test_compression_parity(const std::string &original,
  20380. const std::string &path,
  20381. const std::string &encoding) {
  20382. const std::string compressed =
  20383. compress_payload_for_parity<Compressor>(original);
  20384. Server svr;
  20385. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20386. res.set_content(compressed, "application/octet-stream");
  20387. res.set_header("Content-Encoding", encoding);
  20388. });
  20389. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20390. auto se = detail::scope_exit([&] {
  20391. svr.stop();
  20392. t.join();
  20393. ASSERT_FALSE(svr.is_running());
  20394. });
  20395. svr.wait_until_ready();
  20396. Client cli(HOST, PORT);
  20397. // Non-streaming
  20398. {
  20399. auto res = cli.Get(path);
  20400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20401. EXPECT_EQ(StatusCode::OK_200, res->status);
  20402. EXPECT_EQ(original, res->body);
  20403. }
  20404. // Streaming
  20405. {
  20406. auto h = cli.open_stream("GET", path);
  20407. ASSERT_TRUE(h.is_valid());
  20408. EXPECT_EQ(original, read_all(h));
  20409. }
  20410. }
  20411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20412. TEST(ParityTest, Gzip) {
  20413. test_compression_parity<detail::gzip_compressor>(
  20414. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20415. }
  20416. #endif
  20417. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20418. TEST(ParityTest, Brotli) {
  20419. test_compression_parity<detail::brotli_compressor>(
  20420. "Hello, brotli parity test payload", "/parity-br", "br");
  20421. }
  20422. #endif
  20423. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20424. TEST(ParityTest, Zstd) {
  20425. test_compression_parity<detail::zstd_compressor>(
  20426. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20427. }
  20428. #endif
  20429. //==============================================================================
  20430. // New Stream API Tests
  20431. //==============================================================================
  20432. inline std::string read_body(httplib::stream::Result &result) {
  20433. std::string body;
  20434. while (result.next()) {
  20435. body.append(result.data(), result.size());
  20436. }
  20437. return body;
  20438. }
  20439. TEST(ClientConnectionTest, Basic) {
  20440. httplib::ClientConnection conn;
  20441. EXPECT_FALSE(conn.is_open());
  20442. conn.sock = 1;
  20443. EXPECT_TRUE(conn.is_open());
  20444. httplib::ClientConnection conn2(std::move(conn));
  20445. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20446. conn2.sock = INVALID_SOCKET;
  20447. }
  20448. // Unified test server for all stream::* tests
  20449. class StreamApiTest : public ::testing::Test {
  20450. protected:
  20451. void SetUp() override {
  20452. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20453. res.set_content("Hello World!", "text/plain");
  20454. });
  20455. svr_.Get("/echo-params",
  20456. [](const httplib::Request &req, httplib::Response &res) {
  20457. std::string r;
  20458. for (const auto &p : req.params) {
  20459. if (!r.empty()) r += "&";
  20460. r += p.first + "=" + p.second;
  20461. }
  20462. res.set_content(r, "text/plain");
  20463. });
  20464. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20465. res.set_content(req.body, req.get_header_value("Content-Type"));
  20466. });
  20467. svr_.Post("/echo-headers",
  20468. [](const httplib::Request &req, httplib::Response &res) {
  20469. std::string r;
  20470. for (const auto &h : req.headers)
  20471. r += h.first + ": " + h.second + "\n";
  20472. res.set_content(r, "text/plain");
  20473. });
  20474. svr_.Post("/echo-params",
  20475. [](const httplib::Request &req, httplib::Response &res) {
  20476. std::string r = "params:";
  20477. for (const auto &p : req.params)
  20478. r += p.first + "=" + p.second + ";";
  20479. res.set_content(r + " body:" + req.body, "text/plain");
  20480. });
  20481. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20482. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20483. });
  20484. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20485. res.set_content("PUT:" + req.body, "text/plain");
  20486. });
  20487. svr_.Patch("/echo",
  20488. [](const httplib::Request &req, httplib::Response &res) {
  20489. res.set_content("PATCH:" + req.body, "text/plain");
  20490. });
  20491. svr_.Delete(
  20492. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20493. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20494. "text/plain");
  20495. });
  20496. svr_.Get("/head-test",
  20497. [](const httplib::Request &, httplib::Response &res) {
  20498. res.set_content("body for HEAD", "text/plain");
  20499. });
  20500. svr_.Options("/options",
  20501. [](const httplib::Request &, httplib::Response &res) {
  20502. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20503. });
  20504. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20505. svr_.wait_until_ready();
  20506. }
  20507. void TearDown() override {
  20508. svr_.stop();
  20509. if (thread_.joinable()) thread_.join();
  20510. }
  20511. httplib::Server svr_;
  20512. std::thread thread_;
  20513. };
  20514. // stream::Get tests
  20515. TEST_F(StreamApiTest, GetBasic) {
  20516. httplib::Client cli(HOST, PORT);
  20517. auto result = httplib::stream::Get(cli, "/hello");
  20518. ASSERT_TRUE(result.is_valid());
  20519. EXPECT_EQ(200, result.status());
  20520. EXPECT_EQ("Hello World!", read_body(result));
  20521. }
  20522. TEST_F(StreamApiTest, GetWithParams) {
  20523. httplib::Client cli(HOST, PORT);
  20524. httplib::Params params{{"foo", "bar"}};
  20525. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20526. ASSERT_TRUE(result.is_valid());
  20527. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20528. }
  20529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20530. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20531. httplib::Client cli(HOST, PORT);
  20532. cli.set_payload_max_length(0);
  20533. auto result = httplib::stream::Get(cli, "/hello");
  20534. ASSERT_TRUE(result.is_valid());
  20535. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20536. EXPECT_EQ("Hello World!", read_body(result));
  20537. }
  20538. #endif
  20539. TEST_F(StreamApiTest, GetConnectionError) {
  20540. httplib::Client cli(HOST, 9999);
  20541. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20542. }
  20543. TEST_F(StreamApiTest, Get404) {
  20544. httplib::Client cli(HOST, PORT);
  20545. auto result = httplib::stream::Get(cli, "/nonexistent");
  20546. EXPECT_TRUE(result.is_valid());
  20547. EXPECT_EQ(404, result.status());
  20548. }
  20549. // stream::Post tests
  20550. TEST_F(StreamApiTest, PostBasic) {
  20551. httplib::Client cli(HOST, PORT);
  20552. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20553. "application/json");
  20554. ASSERT_TRUE(result.is_valid());
  20555. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20556. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20557. }
  20558. TEST_F(StreamApiTest, PostWithHeaders) {
  20559. httplib::Client cli(HOST, PORT);
  20560. httplib::Headers headers{{"X-Custom", "value"}};
  20561. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20562. "text/plain");
  20563. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20564. }
  20565. TEST_F(StreamApiTest, PostWithParams) {
  20566. httplib::Client cli(HOST, PORT);
  20567. httplib::Params params{{"k", "v"}};
  20568. auto result =
  20569. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20570. auto body = read_body(result);
  20571. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20572. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20573. }
  20574. TEST_F(StreamApiTest, PostLarge) {
  20575. httplib::Client cli(HOST, PORT);
  20576. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20577. size_t total = 0;
  20578. while (result.next()) {
  20579. total += result.size();
  20580. }
  20581. EXPECT_EQ(100u * 1024u, total);
  20582. }
  20583. // stream::Put/Patch tests
  20584. TEST_F(StreamApiTest, PutAndPatch) {
  20585. httplib::Client cli(HOST, PORT);
  20586. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20587. EXPECT_EQ("PUT:test", read_body(put));
  20588. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20589. EXPECT_EQ("PATCH:test", read_body(patch));
  20590. }
  20591. // stream::Delete tests
  20592. TEST_F(StreamApiTest, Delete) {
  20593. httplib::Client cli(HOST, PORT);
  20594. auto del1 = httplib::stream::Delete(cli, "/resource");
  20595. EXPECT_EQ("Deleted", read_body(del1));
  20596. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20597. EXPECT_EQ("Deleted:data", read_body(del2));
  20598. }
  20599. // stream::Head/Options tests
  20600. TEST_F(StreamApiTest, HeadAndOptions) {
  20601. httplib::Client cli(HOST, PORT);
  20602. auto head = httplib::stream::Head(cli, "/head-test");
  20603. EXPECT_TRUE(head.is_valid());
  20604. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20605. auto opts = httplib::stream::Options(cli, "/options");
  20606. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20607. }
  20608. // SSL stream::* tests
  20609. #ifdef CPPHTTPLIB_SSL_ENABLED
  20610. class SSLStreamApiTest : public ::testing::Test {
  20611. protected:
  20612. void SetUp() override {
  20613. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20614. res.set_content("Hello SSL!", "text/plain");
  20615. });
  20616. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20617. res.set_content(req.body, "text/plain");
  20618. });
  20619. port_ = svr_.bind_to_any_port("127.0.0.1");
  20620. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20621. svr_.wait_until_ready();
  20622. }
  20623. void TearDown() override {
  20624. svr_.stop();
  20625. if (thread_.joinable()) thread_.join();
  20626. }
  20627. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20628. std::thread thread_;
  20629. int port_ = 0;
  20630. };
  20631. TEST_F(SSLStreamApiTest, GetAndPost) {
  20632. httplib::SSLClient cli("127.0.0.1", port_);
  20633. cli.enable_server_certificate_verification(false);
  20634. auto get = httplib::stream::Get(cli, "/hello");
  20635. EXPECT_EQ("Hello SSL!", read_body(get));
  20636. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20637. EXPECT_EQ("test", read_body(post));
  20638. }
  20639. #endif
  20640. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20641. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20642. // BodyReader
  20643. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20644. // Test that read timeout during streaming is detected
  20645. // Use a large content-length response where server delays mid-stream
  20646. Server svr;
  20647. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20648. // Send a large response with delay in the middle
  20649. res.set_content_provider(
  20650. 1000, // content_length
  20651. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20652. if (offset < 100) {
  20653. // Send first 100 bytes immediately
  20654. std::string data(100, 'A');
  20655. sink.write(data.c_str(), data.size());
  20656. return true;
  20657. }
  20658. // Then delay longer than client timeout
  20659. std::this_thread::sleep_for(std::chrono::seconds(3));
  20660. std::string data(900, 'B');
  20661. sink.write(data.c_str(), data.size());
  20662. return true;
  20663. });
  20664. });
  20665. auto port = 8091;
  20666. std::thread t([&]() { svr.listen("localhost", port); });
  20667. svr.wait_until_ready();
  20668. Client cli("localhost", port);
  20669. cli.set_read_timeout(1, 0); // 1 second timeout
  20670. auto handle = cli.open_stream("GET", "/slow-stream");
  20671. ASSERT_TRUE(handle.is_valid());
  20672. char buf[256];
  20673. ssize_t total = 0;
  20674. ssize_t n;
  20675. bool got_error = false;
  20676. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20677. total += n;
  20678. }
  20679. if (n < 0) {
  20680. got_error = true;
  20681. // Should be timeout or read error
  20682. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20683. handle.get_read_error() == Error::Read)
  20684. << "Actual error: " << to_string(handle.get_read_error());
  20685. }
  20686. // Either we got an error, or we got less data than expected
  20687. EXPECT_TRUE(got_error || total < 1000)
  20688. << "Expected timeout but got all " << total << " bytes";
  20689. svr.stop();
  20690. t.join();
  20691. }
  20692. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20693. // Test connection closed detection via BodyReader
  20694. Server svr;
  20695. std::atomic<bool> close_now{false};
  20696. svr.Get("/will-close", [&](const Request &, Response &res) {
  20697. res.set_content_provider(
  20698. 10000, // Large content_length that we won't fully send
  20699. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20700. if (offset < 100) {
  20701. std::string data(100, 'X');
  20702. sink.write(data.c_str(), data.size());
  20703. return true;
  20704. }
  20705. // Wait for signal then abort
  20706. while (!close_now) {
  20707. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20708. }
  20709. return false; // Abort - server will close connection
  20710. });
  20711. });
  20712. auto port = 8092;
  20713. std::thread t([&]() { svr.listen("localhost", port); });
  20714. svr.wait_until_ready();
  20715. Client cli("localhost", port);
  20716. auto handle = cli.open_stream("GET", "/will-close");
  20717. ASSERT_TRUE(handle.is_valid());
  20718. char buf[256];
  20719. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20720. EXPECT_GT(n, 0) << "First read should succeed";
  20721. // Signal server to close
  20722. close_now = true;
  20723. // Keep reading until error or EOF
  20724. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20725. // Keep reading
  20726. }
  20727. // Should get an error since content_length wasn't satisfied
  20728. if (n < 0) {
  20729. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20730. handle.get_read_error() == Error::Read)
  20731. << "Actual error: " << to_string(handle.get_read_error());
  20732. }
  20733. svr.stop();
  20734. t.join();
  20735. }
  20736. #ifdef CPPHTTPLIB_SSL_ENABLED
  20737. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20738. // Test that read timeout during SSL streaming is detected
  20739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20740. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20741. res.set_content_provider(
  20742. 1000, "text/plain",
  20743. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20744. if (offset < 100) {
  20745. std::string data(100, 'A');
  20746. sink.write(data.c_str(), data.size());
  20747. return true;
  20748. }
  20749. std::this_thread::sleep_for(std::chrono::seconds(3));
  20750. std::string data(900, 'B');
  20751. sink.write(data.c_str(), data.size());
  20752. return true;
  20753. });
  20754. });
  20755. auto port = 8093;
  20756. std::thread t([&]() { svr.listen("localhost", port); });
  20757. svr.wait_until_ready();
  20758. SSLClient cli("localhost", port);
  20759. cli.enable_server_certificate_verification(false);
  20760. cli.set_read_timeout(1, 0); // 1 second timeout
  20761. auto handle = cli.open_stream("GET", "/slow-stream");
  20762. ASSERT_TRUE(handle.is_valid());
  20763. char buf[256];
  20764. ssize_t total = 0;
  20765. ssize_t n;
  20766. bool got_error = false;
  20767. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20768. total += n;
  20769. }
  20770. if (n < 0) {
  20771. got_error = true;
  20772. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20773. handle.get_read_error() == Error::Read)
  20774. << "Actual error: " << to_string(handle.get_read_error());
  20775. }
  20776. EXPECT_TRUE(got_error || total < 1000)
  20777. << "Expected timeout but got all " << total << " bytes";
  20778. svr.stop();
  20779. t.join();
  20780. }
  20781. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20782. // Test SSL connection closed detection
  20783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20784. std::atomic<bool> close_now{false};
  20785. svr.Get("/will-close", [&](const Request &, Response &res) {
  20786. res.set_content_provider(
  20787. 10000, "text/plain",
  20788. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20789. if (offset < 100) {
  20790. std::string data(100, 'X');
  20791. sink.write(data.c_str(), data.size());
  20792. return true;
  20793. }
  20794. while (!close_now) {
  20795. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20796. }
  20797. return false;
  20798. });
  20799. });
  20800. auto port = 8094;
  20801. std::thread t([&]() { svr.listen("localhost", port); });
  20802. svr.wait_until_ready();
  20803. SSLClient cli("localhost", port);
  20804. cli.enable_server_certificate_verification(false);
  20805. auto handle = cli.open_stream("GET", "/will-close");
  20806. ASSERT_TRUE(handle.is_valid());
  20807. char buf[256];
  20808. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20809. EXPECT_GT(n, 0);
  20810. // Signal server to close
  20811. close_now = true;
  20812. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20813. // Keep reading
  20814. }
  20815. if (n < 0) {
  20816. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20817. handle.get_read_error() == Error::Read)
  20818. << "Actual error: " << to_string(handle.get_read_error());
  20819. }
  20820. svr.stop();
  20821. t.join();
  20822. }
  20823. #endif
  20824. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20825. using namespace httplib;
  20826. // Create a test file
  20827. const char *fname = "etag_testfile.txt";
  20828. const char *content = "etag-content";
  20829. {
  20830. std::ofstream ofs(fname);
  20831. ofs << content;
  20832. ASSERT_TRUE(ofs.good());
  20833. }
  20834. Server svr;
  20835. svr.set_mount_point("/static", ".");
  20836. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20837. svr.wait_until_ready();
  20838. Client cli(HOST, PORT);
  20839. // First request: should get 200 with ETag header
  20840. auto res1 = cli.Get("/static/etag_testfile.txt");
  20841. ASSERT_TRUE(res1);
  20842. ASSERT_EQ(200, res1->status);
  20843. ASSERT_TRUE(res1->has_header("ETag"));
  20844. std::string etag = res1->get_header_value("ETag");
  20845. EXPECT_FALSE(etag.empty());
  20846. // Verify ETag format: W/"hex-hex"
  20847. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20848. EXPECT_EQ('W', etag[0]);
  20849. EXPECT_EQ('/', etag[1]);
  20850. EXPECT_EQ('"', etag[2]);
  20851. EXPECT_EQ('"', etag.back());
  20852. // Exact match: expect 304 Not Modified
  20853. Headers h2 = {{"If-None-Match", etag}};
  20854. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20855. ASSERT_TRUE(res2);
  20856. EXPECT_EQ(304, res2->status);
  20857. // Wildcard match: expect 304 Not Modified
  20858. Headers h3 = {{"If-None-Match", "*"}};
  20859. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20860. ASSERT_TRUE(res3);
  20861. EXPECT_EQ(304, res3->status);
  20862. // Non-matching ETag: expect 200
  20863. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20864. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20865. ASSERT_TRUE(res4);
  20866. EXPECT_EQ(200, res4->status);
  20867. // Multiple ETags with one matching: expect 304
  20868. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20869. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20870. ASSERT_TRUE(res5);
  20871. EXPECT_EQ(304, res5->status);
  20872. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20873. // that equivalent to the single comma-separated list above, so the match on
  20874. // the second line must still be found.
  20875. Headers h6;
  20876. h6.emplace("If-None-Match", "W/\"other\"");
  20877. h6.emplace("If-None-Match", etag);
  20878. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20879. ASSERT_TRUE(res6);
  20880. EXPECT_EQ(304, res6->status);
  20881. svr.stop();
  20882. t.join();
  20883. std::remove(fname);
  20884. }
  20885. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20886. using namespace httplib;
  20887. Server svr;
  20888. svr.set_mount_point("/static", ".");
  20889. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20890. svr.wait_until_ready();
  20891. Client cli(HOST, PORT);
  20892. // Send If-None-Match: * to a non-existent file
  20893. Headers h = {{"If-None-Match", "*"}};
  20894. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20896. EXPECT_EQ(404, res->status);
  20897. svr.stop();
  20898. t.join();
  20899. }
  20900. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20901. using namespace httplib;
  20902. // Create a test file
  20903. const char *fname = "etag_boundary_testfile.txt";
  20904. const char *content = "boundary-test";
  20905. {
  20906. std::ofstream ofs(fname);
  20907. ofs << content;
  20908. ASSERT_TRUE(ofs.good());
  20909. }
  20910. Server svr;
  20911. svr.set_mount_point("/static", ".");
  20912. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20913. svr.wait_until_ready();
  20914. Client cli(HOST, PORT);
  20915. // Get the actual ETag
  20916. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20917. ASSERT_TRUE(res1);
  20918. ASSERT_EQ(200, res1->status);
  20919. ASSERT_TRUE(res1->has_header("ETag"));
  20920. std::string etag = res1->get_header_value("ETag");
  20921. // Test 1: Very long ETag value (longer than actual ETag)
  20922. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20923. Headers h1 = {{"If-None-Match", "W/"
  20924. "\"very-long-etag-value-that-is-much-longer-"
  20925. "than-the-actual-etag-value\""}};
  20926. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20927. ASSERT_TRUE(res2);
  20928. EXPECT_EQ(200, res2->status); // Should not match
  20929. // Test 2: Long string followed by wildcard
  20930. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20931. // string)
  20932. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20933. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20934. ASSERT_TRUE(res3);
  20935. EXPECT_EQ(304, res3->status); // Should match on "*"
  20936. // Test 3: Wildcard followed by long string
  20937. // Should match on "*" immediately and return 304
  20938. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20939. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20940. ASSERT_TRUE(res4);
  20941. EXPECT_EQ(304, res4->status); // Should match on "*"
  20942. // Test 4: Multiple long non-matching values
  20943. // Should NOT match and return 200 (test that all comparisons are safe)
  20944. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20945. "W/\"second-long-non-matching-value\", "
  20946. "W/\"third-long-non-matching-value\""}};
  20947. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20948. ASSERT_TRUE(res5);
  20949. EXPECT_EQ(200, res5->status); // Should not match
  20950. // Test 5: Single character that is not "*" (edge case)
  20951. Headers h5 = {{"If-None-Match", "X"}};
  20952. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20953. ASSERT_TRUE(res6);
  20954. EXPECT_EQ(200, res6->status); // Should not match
  20955. svr.stop();
  20956. t.join();
  20957. std::remove(fname);
  20958. }
  20959. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20960. using namespace httplib;
  20961. // Create a test file
  20962. const char *fname = "ims_testfile.txt";
  20963. const char *content = "if-modified-since-test";
  20964. {
  20965. std::ofstream ofs(fname);
  20966. ofs << content;
  20967. ASSERT_TRUE(ofs.good());
  20968. }
  20969. Server svr;
  20970. svr.set_mount_point("/static", ".");
  20971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20972. svr.wait_until_ready();
  20973. Client cli(HOST, PORT);
  20974. // First request: should get 200 with Last-Modified header
  20975. auto res1 = cli.Get("/static/ims_testfile.txt");
  20976. ASSERT_TRUE(res1);
  20977. ASSERT_EQ(200, res1->status);
  20978. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20979. std::string last_modified = res1->get_header_value("Last-Modified");
  20980. EXPECT_FALSE(last_modified.empty());
  20981. // If-Modified-Since with same time: expect 304
  20982. Headers h2 = {{"If-Modified-Since", last_modified}};
  20983. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20984. ASSERT_TRUE(res2);
  20985. EXPECT_EQ(304, res2->status);
  20986. // If-Modified-Since with future time: expect 304
  20987. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20988. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20989. ASSERT_TRUE(res3);
  20990. EXPECT_EQ(304, res3->status);
  20991. // If-Modified-Since with past time: expect 200
  20992. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20993. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20994. ASSERT_TRUE(res4);
  20995. EXPECT_EQ(200, res4->status);
  20996. // If-None-Match takes precedence over If-Modified-Since
  20997. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20998. ASSERT_TRUE(res1->has_header("ETag"));
  20999. std::string etag = res1->get_header_value("ETag");
  21000. Headers h5 = {{"If-None-Match", etag},
  21001. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21002. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21003. ASSERT_TRUE(res5);
  21004. EXPECT_EQ(304, res5->status);
  21005. svr.stop();
  21006. t.join();
  21007. std::remove(fname);
  21008. }
  21009. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21010. using namespace httplib;
  21011. Server svr;
  21012. // Endpoint that returns compressible content
  21013. svr.Get("/compressible", [](const Request &, Response &res) {
  21014. // Return a large enough body to trigger compression
  21015. std::string body(1000, 'a');
  21016. res.set_content(body, "text/plain");
  21017. });
  21018. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21019. svr.wait_until_ready();
  21020. Client cli(HOST, PORT);
  21021. // Request with gzip support: should get Vary header when compressed
  21022. cli.set_compress(true);
  21023. auto res1 = cli.Get("/compressible");
  21024. ASSERT_TRUE(res1);
  21025. EXPECT_EQ(200, res1->status);
  21026. // If Content-Encoding is set, Vary should also be set
  21027. if (res1->has_header("Content-Encoding")) {
  21028. EXPECT_TRUE(res1->has_header("Vary"));
  21029. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21030. }
  21031. // Request without Accept-Encoding header: should not have compression
  21032. Headers h_no_compress;
  21033. auto res2 = cli.Get("/compressible", h_no_compress);
  21034. ASSERT_TRUE(res2);
  21035. EXPECT_EQ(200, res2->status);
  21036. // Verify Vary header is present when compression is applied
  21037. // (the exact behavior depends on server configuration)
  21038. svr.stop();
  21039. t.join();
  21040. }
  21041. TEST(ETagTest, IfRangeWithETag) {
  21042. using namespace httplib;
  21043. // Create a test file with known content
  21044. const char *fname = "if_range_testfile.txt";
  21045. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21046. {
  21047. std::ofstream ofs(fname);
  21048. ofs << content;
  21049. ASSERT_TRUE(ofs.good());
  21050. }
  21051. Server svr;
  21052. svr.set_mount_point("/static", ".");
  21053. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21054. svr.wait_until_ready();
  21055. Client cli(HOST, PORT);
  21056. // First request: get ETag
  21057. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21058. ASSERT_TRUE(res1);
  21059. ASSERT_EQ(200, res1->status);
  21060. ASSERT_TRUE(res1->has_header("ETag"));
  21061. std::string etag = res1->get_header_value("ETag");
  21062. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21063. // Since our server generates weak ETags (W/"..."), If-Range with our
  21064. // ETag should NOT result in partial content - it should return full content.
  21065. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21066. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21067. ASSERT_TRUE(res2);
  21068. // Weak ETag in If-Range -> full content (200), not partial (206)
  21069. EXPECT_EQ(200, res2->status);
  21070. EXPECT_EQ(content, res2->body);
  21071. EXPECT_FALSE(res2->has_header("Content-Range"));
  21072. // Range request with non-matching If-Range (ETag): should get 200 (full
  21073. // content)
  21074. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21075. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21076. ASSERT_TRUE(res3);
  21077. EXPECT_EQ(200, res3->status);
  21078. EXPECT_EQ(content, res3->body);
  21079. EXPECT_FALSE(res3->has_header("Content-Range"));
  21080. // Range request with strong ETag (hypothetical - our server doesn't generate
  21081. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21082. // should return full content)
  21083. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21084. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21085. ASSERT_TRUE(res4);
  21086. EXPECT_EQ(200, res4->status);
  21087. EXPECT_EQ(content, res4->body);
  21088. EXPECT_FALSE(res4->has_header("Content-Range"));
  21089. svr.stop();
  21090. t.join();
  21091. std::remove(fname);
  21092. }
  21093. TEST(ETagTest, IfRangeWithDate) {
  21094. using namespace httplib;
  21095. // Create a test file
  21096. const char *fname = "if_range_date_testfile.txt";
  21097. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21098. {
  21099. std::ofstream ofs(fname);
  21100. ofs << content;
  21101. ASSERT_TRUE(ofs.good());
  21102. }
  21103. Server svr;
  21104. svr.set_mount_point("/static", ".");
  21105. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21106. svr.wait_until_ready();
  21107. Client cli(HOST, PORT);
  21108. // First request: get Last-Modified
  21109. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21110. ASSERT_TRUE(res1);
  21111. ASSERT_EQ(200, res1->status);
  21112. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21113. std::string last_modified = res1->get_header_value("Last-Modified");
  21114. // Range request with matching If-Range (date): should get 206
  21115. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21116. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21117. ASSERT_TRUE(res2);
  21118. EXPECT_EQ(206, res2->status);
  21119. EXPECT_EQ("FGHIJ", res2->body);
  21120. // Range request with old If-Range date: should get 200 (full content)
  21121. Headers h3 = {{"Range", "bytes=5-9"},
  21122. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21123. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21124. ASSERT_TRUE(res3);
  21125. EXPECT_EQ(200, res3->status);
  21126. EXPECT_EQ(content, res3->body);
  21127. // Range request with future If-Range date: should get 206
  21128. Headers h4 = {{"Range", "bytes=0-4"},
  21129. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21130. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21131. ASSERT_TRUE(res4);
  21132. EXPECT_EQ(206, res4->status);
  21133. EXPECT_EQ("ABCDE", res4->body);
  21134. svr.stop();
  21135. t.join();
  21136. std::remove(fname);
  21137. }
  21138. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21139. using namespace httplib;
  21140. const char *fname = "etag_malformed.txt";
  21141. const char *content = "malformed-etag";
  21142. {
  21143. std::ofstream ofs(fname);
  21144. ofs << content;
  21145. ASSERT_TRUE(ofs.good());
  21146. }
  21147. Server svr;
  21148. svr.set_mount_point("/static", ".");
  21149. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21150. svr.wait_until_ready();
  21151. Client cli(HOST, PORT);
  21152. // baseline: should get 200 and an ETag
  21153. auto res1 = cli.Get("/static/etag_malformed.txt");
  21154. ASSERT_TRUE(res1);
  21155. ASSERT_EQ(200, res1->status);
  21156. ASSERT_TRUE(res1->has_header("ETag"));
  21157. // Malformed ETag value (missing quotes) should be treated as non-matching
  21158. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21159. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21160. ASSERT_TRUE(res_bad);
  21161. EXPECT_EQ(200, res_bad->status);
  21162. // Whitespace-only header value should be considered invalid / non-matching
  21163. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21164. "Host: localhost\r\n"
  21165. "If-None-Match: \r\n"
  21166. "Connection: close\r\n"
  21167. "\r\n";
  21168. std::string out;
  21169. ASSERT_TRUE(send_request(5, raw_req, &out));
  21170. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21171. svr.stop();
  21172. t.join();
  21173. std::remove(fname);
  21174. }
  21175. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21176. using namespace httplib;
  21177. const char *fname = "ims_invalid_format.txt";
  21178. const char *content = "ims-bad-format";
  21179. {
  21180. std::ofstream ofs(fname);
  21181. ofs << content;
  21182. ASSERT_TRUE(ofs.good());
  21183. }
  21184. Server svr;
  21185. svr.set_mount_point("/static", ".");
  21186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21187. svr.wait_until_ready();
  21188. Client cli(HOST, PORT);
  21189. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21190. ASSERT_TRUE(res1);
  21191. ASSERT_EQ(200, res1->status);
  21192. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21193. // If-Modified-Since with invalid format should not result in 304
  21194. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21195. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21196. ASSERT_TRUE(res_bad);
  21197. EXPECT_EQ(200, res_bad->status);
  21198. // If-Range with invalid date format should be treated as mismatch -> full
  21199. // content (200)
  21200. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21201. {"If-Range", "invalid-date"}};
  21202. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21203. ASSERT_TRUE(res_ifrange);
  21204. EXPECT_EQ(200, res_ifrange->status);
  21205. svr.stop();
  21206. t.join();
  21207. std::remove(fname);
  21208. }
  21209. TEST(ETagTest, IfRangeWithMalformedETag) {
  21210. using namespace httplib;
  21211. const char *fname = "ifrange_malformed.txt";
  21212. const std::string content = "0123456789";
  21213. {
  21214. std::ofstream ofs(fname);
  21215. ofs << content;
  21216. ASSERT_TRUE(ofs.good());
  21217. }
  21218. Server svr;
  21219. svr.set_mount_point("/static", ".");
  21220. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21221. svr.wait_until_ready();
  21222. Client cli(HOST, PORT);
  21223. // First request: get ETag
  21224. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21225. ASSERT_TRUE(res1);
  21226. ASSERT_EQ(200, res1->status);
  21227. ASSERT_TRUE(res1->has_header("ETag"));
  21228. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21229. // full content (200)
  21230. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21231. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21232. ASSERT_TRUE(res2);
  21233. EXPECT_EQ(200, res2->status);
  21234. EXPECT_EQ(content, res2->body);
  21235. svr.stop();
  21236. t.join();
  21237. std::remove(fname);
  21238. }
  21239. TEST(ETagTest, ExtremeLargeDateValues) {
  21240. using namespace httplib;
  21241. const char *fname = "ims_extreme_date.txt";
  21242. const char *content = "ims-extreme-date";
  21243. {
  21244. std::ofstream ofs(fname);
  21245. ofs << content;
  21246. ASSERT_TRUE(ofs.good());
  21247. }
  21248. Server svr;
  21249. svr.set_mount_point("/static", ".");
  21250. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21251. svr.wait_until_ready();
  21252. Client cli(HOST, PORT);
  21253. auto res1 = cli.Get(std::string("/static/") + fname);
  21254. ASSERT_TRUE(res1);
  21255. ASSERT_EQ(200, res1->status);
  21256. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21257. // Extremely large year that may overflow date parsing routines.
  21258. Headers h_large_date = {
  21259. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21260. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21261. ASSERT_TRUE(res_bad);
  21262. // Expect server to treat this as invalid/mismatch and return full content
  21263. EXPECT_EQ(200, res_bad->status);
  21264. // If-Range with extremely large date should be treated as mismatch -> full
  21265. // content (200)
  21266. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21267. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21268. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21269. ASSERT_TRUE(res_ifrange);
  21270. EXPECT_EQ(200, res_ifrange->status);
  21271. svr.stop();
  21272. t.join();
  21273. std::remove(fname);
  21274. }
  21275. TEST(ETagTest, NegativeFileModificationTime) {
  21276. using namespace httplib;
  21277. const char *fname = "ims_negative_mtime.txt";
  21278. const std::string content = "negative-mtime";
  21279. {
  21280. std::ofstream ofs(fname);
  21281. ofs << content;
  21282. ASSERT_TRUE(ofs.good());
  21283. }
  21284. // Try to set file mtime to a negative value. This may fail on some
  21285. // platforms/filesystems; if it fails, the test will still verify server
  21286. // behaves safely by performing a regular conditional request.
  21287. #if defined(__APPLE__) || defined(__linux__)
  21288. bool set_negative = false;
  21289. do {
  21290. struct timeval times[2];
  21291. // access time: now
  21292. times[0].tv_sec = time(nullptr);
  21293. times[0].tv_usec = 0;
  21294. // modification time: negative (e.g., -1)
  21295. times[1].tv_sec = -1;
  21296. times[1].tv_usec = 0;
  21297. if (utimes(fname, times) == 0) { set_negative = true; }
  21298. } while (0);
  21299. #else
  21300. bool set_negative = false;
  21301. #endif
  21302. Server svr;
  21303. svr.set_mount_point("/static", ".");
  21304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21305. svr.wait_until_ready();
  21306. Client cli(HOST, PORT);
  21307. auto res1 = cli.Get(std::string("/static/") + fname);
  21308. ASSERT_TRUE(res1);
  21309. ASSERT_EQ(200, res1->status);
  21310. bool has_last_modified = res1->has_header("Last-Modified");
  21311. std::string last_modified;
  21312. if (has_last_modified) {
  21313. last_modified = res1->get_header_value("Last-Modified");
  21314. }
  21315. if (set_negative) {
  21316. // If we successfully set a negative mtime, ensure server returns a
  21317. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21318. // with an old date and ensure server handles it without crash.
  21319. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21320. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21321. ASSERT_TRUE(res2);
  21322. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21323. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21324. } else {
  21325. // Could not set negative mtime on this platform; fall back to verifying
  21326. // that normal invalid/malformed dates are treated safely (non-304).
  21327. Headers h_bad_date = {
  21328. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21329. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21330. ASSERT_TRUE(res_bad);
  21331. EXPECT_EQ(200, res_bad->status);
  21332. }
  21333. svr.stop();
  21334. t.join();
  21335. std::remove(fname);
  21336. }
  21337. //==============================================================================
  21338. // Integration Tests with Server
  21339. //==============================================================================
  21340. class SSEIntegrationTest : public ::testing::Test {
  21341. protected:
  21342. void SetUp() override {
  21343. stop_server_.store(false);
  21344. events_.clear();
  21345. server_ = httplib::detail::make_unique<Server>();
  21346. setup_server();
  21347. start_server();
  21348. }
  21349. void TearDown() override {
  21350. stop_server_.store(true);
  21351. event_cv_.notify_all();
  21352. server_->stop();
  21353. if (server_thread_.joinable()) { server_thread_.join(); }
  21354. }
  21355. void setup_server() {
  21356. // Simple SSE endpoint
  21357. server_->Get("/events", [this](const Request &req, Response &res) {
  21358. auto last_id = req.get_header_value("Last-Event-ID");
  21359. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21360. res.set_chunked_content_provider(
  21361. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21362. std::unique_lock<std::mutex> lock(event_mutex_);
  21363. if (event_cv_.wait_for(
  21364. lock, std::chrono::milliseconds(200), [this] {
  21365. return !events_.empty() || stop_server_.load();
  21366. })) {
  21367. if (stop_server_.load()) { return false; }
  21368. if (!events_.empty()) {
  21369. std::string event = events_.front();
  21370. events_.erase(events_.begin());
  21371. sink.write(event.data(), event.size());
  21372. return true;
  21373. }
  21374. }
  21375. return !stop_server_.load();
  21376. });
  21377. });
  21378. // Endpoint that returns error
  21379. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21380. res.status = 500;
  21381. res.set_content("Internal Server Error", "text/plain");
  21382. });
  21383. // Endpoint for custom event types
  21384. server_->Get("/custom-events", [](const Request &, Response &res) {
  21385. res.set_chunked_content_provider(
  21386. "text/event-stream", [](size_t offset, DataSink &sink) {
  21387. if (offset == 0) {
  21388. std::string event = "event: update\ndata: updated\n\n"
  21389. "event: delete\ndata: deleted\n\n";
  21390. sink.write(event.data(), event.size());
  21391. }
  21392. return false; // End stream after sending
  21393. });
  21394. });
  21395. }
  21396. void start_server() {
  21397. port_ = server_->bind_to_any_port(HOST);
  21398. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21399. // Wait for server to start
  21400. while (!server_->is_running()) {
  21401. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21402. }
  21403. }
  21404. int get_port() const { return port_; }
  21405. void send_event(const std::string &event) {
  21406. std::lock_guard<std::mutex> lock(event_mutex_);
  21407. events_.push_back(event);
  21408. event_cv_.notify_all();
  21409. }
  21410. std::unique_ptr<Server> server_;
  21411. std::thread server_thread_;
  21412. std::mutex event_mutex_;
  21413. std::condition_variable event_cv_;
  21414. std::vector<std::string> events_;
  21415. std::atomic<bool> stop_server_{false};
  21416. std::string last_received_event_id_;
  21417. int port_ = 0;
  21418. };
  21419. //==============================================================================
  21420. // SSE Parsing Tests
  21421. //==============================================================================
  21422. class SSEParsingTest : public SSEIntegrationTest {
  21423. protected:
  21424. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21425. // A trailing sentinel event tells when the whole stream has been parsed.
  21426. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21427. auto body = stream + "event: end\ndata: end\n\n";
  21428. server_->Get("/parse", [body](const Request &, Response &res) {
  21429. res.set_content(body, "text/event-stream");
  21430. });
  21431. return collect("/parse");
  21432. }
  21433. // Runs SSEClient against path until an "end" event arrives and returns the
  21434. // messages dispatched before it
  21435. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21436. Client client(HOST, get_port());
  21437. sse::SSEClient sse(client, path);
  21438. std::mutex mutex;
  21439. std::condition_variable cv;
  21440. std::vector<sse::SSEMessage> messages;
  21441. auto done = false;
  21442. sse.on_message([&](const sse::SSEMessage &msg) {
  21443. std::lock_guard<std::mutex> lock(mutex);
  21444. // Ignore a replay from a reconnect that races with stop()
  21445. if (!done) { messages.push_back(msg); }
  21446. });
  21447. sse.on_event("end", [&](const sse::SSEMessage &) {
  21448. std::lock_guard<std::mutex> lock(mutex);
  21449. done = true;
  21450. cv.notify_all();
  21451. });
  21452. sse.set_reconnect_interval(100);
  21453. sse.start_async();
  21454. {
  21455. std::unique_lock<std::mutex> lock(mutex);
  21456. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21457. }
  21458. sse.stop();
  21459. EXPECT_TRUE(done);
  21460. return messages;
  21461. }
  21462. };
  21463. TEST_F(SSEParsingTest, SingleLineData) {
  21464. auto msgs = parse("data: hello\n\n");
  21465. ASSERT_EQ(msgs.size(), 1u);
  21466. EXPECT_EQ(msgs[0].data, "hello");
  21467. EXPECT_EQ(msgs[0].event, "message");
  21468. }
  21469. TEST_F(SSEParsingTest, MultiLineData) {
  21470. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21471. ASSERT_EQ(msgs.size(), 1u);
  21472. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21473. }
  21474. TEST_F(SSEParsingTest, CustomEventType) {
  21475. auto msgs = parse("event: update\ndata: payload\n\n");
  21476. ASSERT_EQ(msgs.size(), 1u);
  21477. EXPECT_EQ(msgs[0].event, "update");
  21478. EXPECT_EQ(msgs[0].data, "payload");
  21479. }
  21480. TEST_F(SSEParsingTest, EventIdHandling) {
  21481. auto msgs = parse("id: 12345\ndata: test\n\n");
  21482. ASSERT_EQ(msgs.size(), 1u);
  21483. EXPECT_EQ(msgs[0].id, "12345");
  21484. }
  21485. TEST_F(SSEParsingTest, EmptyEventId) {
  21486. auto msgs = parse("id:\ndata: test\n\n");
  21487. ASSERT_EQ(msgs.size(), 1u);
  21488. EXPECT_EQ(msgs[0].id, "");
  21489. }
  21490. TEST_F(SSEParsingTest, CommentsIgnored) {
  21491. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21492. ASSERT_EQ(msgs.size(), 1u);
  21493. EXPECT_EQ(msgs[0].data, "hello");
  21494. EXPECT_EQ(msgs[0].event, "message");
  21495. }
  21496. TEST_F(SSEParsingTest, ColonInValue) {
  21497. auto msgs = parse("data: hello:world:test\n\n");
  21498. ASSERT_EQ(msgs.size(), 1u);
  21499. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21500. }
  21501. TEST_F(SSEParsingTest, FieldNameOnly) {
  21502. // A line without a colon is a field name with an empty value
  21503. auto msgs = parse("data\n\n");
  21504. ASSERT_EQ(msgs.size(), 1u);
  21505. EXPECT_EQ(msgs[0].data, "");
  21506. }
  21507. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21508. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21509. ASSERT_EQ(msgs.size(), 1u);
  21510. EXPECT_EQ(msgs[0].event, "update");
  21511. EXPECT_EQ(msgs[0].data, "hello");
  21512. }
  21513. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21514. auto msgs = parse("data\r\n\r\n");
  21515. ASSERT_EQ(msgs.size(), 1u);
  21516. EXPECT_EQ(msgs[0].data, "");
  21517. }
  21518. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21519. auto msgs = parse("event: update\rdata: hello\r\r");
  21520. ASSERT_EQ(msgs.size(), 1u);
  21521. EXPECT_EQ(msgs[0].event, "update");
  21522. EXPECT_EQ(msgs[0].data, "hello");
  21523. }
  21524. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21525. // Chunk boundaries fall inside every \r\n and right before the first one
  21526. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21527. "\n\r", "\nevent: end\ndata: end\n\n"};
  21528. server_->Get("/split", [chunks](const Request &, Response &res) {
  21529. auto i = std::make_shared<size_t>(0);
  21530. res.set_chunked_content_provider(
  21531. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21532. if (*i == chunks.size()) {
  21533. sink.done();
  21534. } else {
  21535. sink.write(chunks[*i].data(), chunks[*i].size());
  21536. (*i)++;
  21537. }
  21538. return true;
  21539. });
  21540. });
  21541. auto msgs = collect("/split");
  21542. ASSERT_EQ(msgs.size(), 1u);
  21543. EXPECT_EQ(msgs[0].event, "update");
  21544. EXPECT_EQ(msgs[0].data, "hello");
  21545. }
  21546. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21547. // Only a BOM at the start of the stream is ignored
  21548. auto msgs = parse("\xEF\xBB\xBF"
  21549. "data: first\n\n"
  21550. "\xEF\xBB\xBF"
  21551. "data: second\n\n");
  21552. ASSERT_EQ(msgs.size(), 1u);
  21553. EXPECT_EQ(msgs[0].data, "first");
  21554. }
  21555. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21556. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21557. ASSERT_EQ(msgs.size(), 1u);
  21558. EXPECT_EQ(msgs[0].data, "hello");
  21559. EXPECT_EQ(msgs[0].event, "message");
  21560. }
  21561. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21562. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21563. ASSERT_EQ(msgs.size(), 2u);
  21564. EXPECT_EQ(msgs[0].data, "hello");
  21565. EXPECT_EQ(msgs[1].data, "hello");
  21566. }
  21567. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21568. // An event without data is not dispatched, and its type must not leak
  21569. // into the next event
  21570. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21571. ASSERT_EQ(msgs.size(), 1u);
  21572. EXPECT_EQ(msgs[0].event, "message");
  21573. EXPECT_EQ(msgs[0].data, "hello");
  21574. }
  21575. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21576. // Also when the empty field replaces an earlier type
  21577. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21578. ASSERT_EQ(msgs.size(), 2u);
  21579. EXPECT_EQ(msgs[0].event, "message");
  21580. EXPECT_EQ(msgs[1].event, "message");
  21581. }
  21582. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21583. // The first connection sends only an id; the second echoes back the
  21584. // Last-Event-ID it was reconnected with
  21585. std::atomic<int> connection_count{0};
  21586. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21587. if (connection_count++ == 0) {
  21588. res.set_content("id: 42\n\n", "text/event-stream");
  21589. } else {
  21590. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21591. "\n\nevent: end\ndata: end\n\n",
  21592. "text/event-stream");
  21593. }
  21594. });
  21595. auto msgs = collect("/id-only");
  21596. ASSERT_EQ(msgs.size(), 1u);
  21597. EXPECT_EQ(msgs[0].data, "42");
  21598. }
  21599. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21600. // The first connection sets an id and then clears it with an empty one; the
  21601. // second reports whether it was reconnected with a Last-Event-ID
  21602. std::atomic<int> connection_count{0};
  21603. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21604. if (connection_count++ == 0) {
  21605. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21606. "text/event-stream");
  21607. } else {
  21608. res.set_content(
  21609. std::string("data: ") +
  21610. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21611. "\n\nevent: end\ndata: end\n\n",
  21612. "text/event-stream");
  21613. }
  21614. });
  21615. auto msgs = collect("/id-clear");
  21616. ASSERT_EQ(msgs.size(), 3u);
  21617. EXPECT_EQ(msgs[0].id, "1");
  21618. EXPECT_EQ(msgs[1].id, "");
  21619. EXPECT_EQ(msgs[2].data, "not sent");
  21620. }
  21621. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21622. // The first connection sets an id and then sends ids that cannot be carried
  21623. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21624. // with
  21625. std::atomic<int> connection_count{0};
  21626. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21627. if (connection_count++ == 0) {
  21628. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21629. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21630. "text/event-stream");
  21631. } else {
  21632. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21633. "\n\nevent: end\ndata: end\n\n",
  21634. "text/event-stream");
  21635. }
  21636. });
  21637. auto msgs = collect("/id-unsendable");
  21638. ASSERT_EQ(msgs.size(), 1u);
  21639. EXPECT_EQ(msgs[0].data, "42");
  21640. }
  21641. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21642. auto msgs = parse("event: notification\nid: evt-42\n"
  21643. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21644. ASSERT_EQ(msgs.size(), 1u);
  21645. EXPECT_EQ(msgs[0].event, "notification");
  21646. EXPECT_EQ(msgs[0].id, "evt-42");
  21647. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21648. }
  21649. TEST(SSEMessageTest, Clear) {
  21650. sse::SSEMessage msg;
  21651. msg.event = "custom";
  21652. msg.data = "some data";
  21653. msg.id = "123";
  21654. msg.clear();
  21655. EXPECT_EQ(msg.event, "message");
  21656. EXPECT_EQ(msg.data, "");
  21657. EXPECT_EQ(msg.id, "");
  21658. }
  21659. //==============================================================================
  21660. // SSE Integration Tests
  21661. //==============================================================================
  21662. // Test: Successful connection and on_open callback
  21663. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21664. // Add a simple endpoint that sends one event and closes
  21665. server_->Get("/simple-event", [](const Request &, Response &res) {
  21666. res.set_chunked_content_provider(
  21667. "text/event-stream", [](size_t offset, DataSink &sink) {
  21668. if (offset == 0) {
  21669. std::string event = "data: hello\n\n";
  21670. sink.write(event.data(), event.size());
  21671. }
  21672. return false; // Close stream after sending
  21673. });
  21674. });
  21675. Client client("localhost", get_port());
  21676. sse::SSEClient sse(client, "/simple-event");
  21677. std::atomic<bool> open_called{false};
  21678. std::atomic<bool> message_received{false};
  21679. sse.on_open([&open_called]() { open_called.store(true); });
  21680. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21681. if (msg.data == "hello") { message_received.store(true); }
  21682. });
  21683. sse.set_reconnect_interval(100);
  21684. sse.set_max_reconnect_attempts(1);
  21685. // Start async
  21686. sse.start_async();
  21687. // Wait for message to be processed
  21688. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21689. sse.stop();
  21690. EXPECT_TRUE(open_called.load());
  21691. EXPECT_TRUE(message_received.load());
  21692. }
  21693. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21694. // A data line that never ends.
  21695. server_->Get("/endless-line", [](const Request &, Response &res) {
  21696. res.set_chunked_content_provider(
  21697. "text/event-stream", [](size_t offset, DataSink &sink) {
  21698. if (offset == 0) { sink.write("data: ", 6); }
  21699. std::string chunk(64 * 1024, 'A');
  21700. return sink.write(chunk.data(), chunk.size());
  21701. });
  21702. });
  21703. Client client("localhost", get_port());
  21704. sse::SSEClient sse(client, "/endless-line");
  21705. std::atomic<bool> too_long{false};
  21706. sse.on_error([&](Error err) {
  21707. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21708. });
  21709. sse.set_max_reconnect_attempts(1);
  21710. sse.start_async();
  21711. for (int i = 0; i < 500 && !too_long; i++) {
  21712. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21713. }
  21714. sse.stop();
  21715. EXPECT_TRUE(too_long);
  21716. }
  21717. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21718. // Far more in all than the client's payload limit below.
  21719. server_->Get("/many-events", [](const Request &, Response &res) {
  21720. res.set_chunked_content_provider(
  21721. "text/event-stream", [](size_t offset, DataSink &sink) {
  21722. if (offset == 0) {
  21723. std::string events;
  21724. for (int i = 0; i < 1000; i++) {
  21725. events += "data: message\n\n";
  21726. }
  21727. sink.write(events.data(), events.size());
  21728. }
  21729. return false;
  21730. });
  21731. });
  21732. Client client("localhost", get_port());
  21733. client.set_payload_max_length(1024);
  21734. sse::SSEClient sse(client, "/many-events");
  21735. std::atomic<int> messages{0};
  21736. std::atomic<bool> too_large{false};
  21737. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21738. sse.on_error([&](Error err) {
  21739. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21740. });
  21741. sse.set_max_reconnect_attempts(1);
  21742. sse.start_async();
  21743. for (int i = 0; i < 500 && messages < 1000; i++) {
  21744. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21745. }
  21746. sse.stop();
  21747. EXPECT_GE(messages.load(), 1000);
  21748. EXPECT_FALSE(too_large);
  21749. }
  21750. // Test: on_message callback
  21751. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21752. // Endpoint that sends multiple events then closes
  21753. server_->Get("/multi-event", [](const Request &, Response &res) {
  21754. res.set_chunked_content_provider(
  21755. "text/event-stream", [](size_t offset, DataSink &sink) {
  21756. if (offset == 0) {
  21757. std::string events = "data: message1\n\ndata: message2\n\n";
  21758. sink.write(events.data(), events.size());
  21759. }
  21760. return false;
  21761. });
  21762. });
  21763. Client client("localhost", get_port());
  21764. sse::SSEClient sse(client, "/multi-event");
  21765. std::vector<std::string> received_messages;
  21766. std::mutex messages_mutex;
  21767. sse.on_message([&](const sse::SSEMessage &msg) {
  21768. std::lock_guard<std::mutex> lock(messages_mutex);
  21769. received_messages.push_back(msg.data);
  21770. });
  21771. sse.set_reconnect_interval(100);
  21772. sse.set_max_reconnect_attempts(1);
  21773. sse.start_async();
  21774. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21775. sse.stop();
  21776. std::lock_guard<std::mutex> lock(messages_mutex);
  21777. EXPECT_GE(received_messages.size(), 2u);
  21778. if (received_messages.size() >= 2) {
  21779. EXPECT_EQ(received_messages[0], "message1");
  21780. EXPECT_EQ(received_messages[1], "message2");
  21781. }
  21782. }
  21783. // Test: on_event for specific types
  21784. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21785. Client client("localhost", get_port());
  21786. sse::SSEClient sse(client, "/custom-events");
  21787. std::atomic<bool> update_received{false};
  21788. std::atomic<bool> delete_received{false};
  21789. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21790. if (msg.data == "updated") { update_received.store(true); }
  21791. });
  21792. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21793. if (msg.data == "deleted") { delete_received.store(true); }
  21794. });
  21795. sse.set_max_reconnect_attempts(1);
  21796. sse.start_async();
  21797. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21798. sse.stop();
  21799. EXPECT_TRUE(update_received.load());
  21800. EXPECT_TRUE(delete_received.load());
  21801. }
  21802. // Test: on_error callback on connection failure
  21803. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21804. // Connect to a non-existent port
  21805. Client client("localhost", 59999);
  21806. sse::SSEClient sse(client, "/events");
  21807. std::atomic<bool> error_called{false};
  21808. Error received_error = Error::Success;
  21809. sse.on_error([&](Error err) {
  21810. error_called.store(true);
  21811. received_error = err;
  21812. });
  21813. sse.set_reconnect_interval(50);
  21814. sse.set_max_reconnect_attempts(1);
  21815. sse.start_async();
  21816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21817. sse.stop();
  21818. EXPECT_TRUE(error_called.load());
  21819. EXPECT_NE(received_error, Error::Success);
  21820. }
  21821. // Test: Last-Event-ID header sent on reconnect
  21822. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21823. // Endpoint that sends event with ID
  21824. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21825. res.set_chunked_content_provider(
  21826. "text/event-stream", [](size_t offset, DataSink &sink) {
  21827. if (offset == 0) {
  21828. std::string event = "id: evt-123\ndata: test\n\n";
  21829. sink.write(event.data(), event.size());
  21830. }
  21831. return false;
  21832. });
  21833. });
  21834. Client client("localhost", get_port());
  21835. sse::SSEClient sse(client, "/event-with-id");
  21836. std::atomic<bool> id_received{false};
  21837. sse.on_message([&](const sse::SSEMessage &msg) {
  21838. if (!msg.id.empty()) { id_received.store(true); }
  21839. });
  21840. sse.set_reconnect_interval(100);
  21841. sse.set_max_reconnect_attempts(1);
  21842. sse.start_async();
  21843. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21844. sse.stop();
  21845. EXPECT_TRUE(id_received.load());
  21846. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21847. }
  21848. // Test: Manual stop
  21849. TEST_F(SSEIntegrationTest, ManualStop) {
  21850. // Endpoint that sends one event and stays open briefly. The server outlives
  21851. // this test body, so the provider uses the fixture's flag, not a local.
  21852. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21853. res.set_chunked_content_provider(
  21854. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21855. if (offset == 0) {
  21856. std::string event = "data: connected\n\n";
  21857. sink.write(event.data(), event.size());
  21858. }
  21859. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21860. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21861. }
  21862. return false;
  21863. });
  21864. });
  21865. Client client("localhost", get_port());
  21866. sse::SSEClient sse(client, "/stay-open");
  21867. std::atomic<bool> connected{false};
  21868. sse.on_open([&connected]() { connected.store(true); });
  21869. sse.set_reconnect_interval(100);
  21870. sse.set_max_reconnect_attempts(1);
  21871. sse.start_async();
  21872. // Wait for connection to establish
  21873. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21874. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21875. }
  21876. EXPECT_TRUE(connected.load());
  21877. EXPECT_TRUE(sse.is_connected());
  21878. // Signal handler to stop
  21879. stop_server_.store(true);
  21880. // Stop SSE client
  21881. sse.stop();
  21882. EXPECT_FALSE(sse.is_connected());
  21883. }
  21884. // Sends one event, then nothing until stop is set
  21885. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21886. return [&stop](const Request &, Response &res) {
  21887. res.set_chunked_content_provider(
  21888. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21889. if (offset == 0) {
  21890. std::string event = "data: hello\n\n";
  21891. sink.write(event.data(), event.size());
  21892. }
  21893. while (!stop.load()) {
  21894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21895. }
  21896. return false;
  21897. });
  21898. };
  21899. }
  21900. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21901. static void check_stop_interrupts_blocked_read(Client &client) {
  21902. client.set_read_timeout(30, 0);
  21903. for (auto by_destructor : {false, true}) {
  21904. std::atomic<bool> received{false};
  21905. std::chrono::steady_clock::time_point start;
  21906. {
  21907. sse::SSEClient sse(client, "/idle-stream");
  21908. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21909. sse.start_async();
  21910. for (int i = 0; i < 500 && !received.load(); ++i) {
  21911. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21912. }
  21913. ASSERT_TRUE(received.load());
  21914. // Let the client block in the next read
  21915. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21916. start = std::chrono::steady_clock::now();
  21917. if (!by_destructor) { sse.stop(); }
  21918. }
  21919. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21920. std::chrono::seconds(2));
  21921. }
  21922. }
  21923. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21924. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21925. Client client("localhost", get_port());
  21926. check_stop_interrupts_blocked_read(client);
  21927. }
  21928. #ifdef CPPHTTPLIB_SSL_ENABLED
  21929. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21931. std::atomic<bool> done{false};
  21932. svr.Get("/idle-stream", idle_event_stream(done));
  21933. auto port = svr.bind_to_any_port(HOST);
  21934. std::thread t([&] { svr.listen_after_bind(); });
  21935. auto se = detail::scope_exit([&] {
  21936. done.store(true);
  21937. svr.stop();
  21938. t.join();
  21939. });
  21940. svr.wait_until_ready();
  21941. Client client("https://localhost:" + std::to_string(port));
  21942. client.enable_server_certificate_verification(false);
  21943. check_stop_interrupts_blocked_read(client);
  21944. }
  21945. #endif
  21946. // Test: SSEClient with custom headers
  21947. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21948. // Setup a server endpoint that checks for custom header
  21949. std::atomic<bool> header_received{false};
  21950. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21951. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21952. header_received.store(true);
  21953. }
  21954. res.set_chunked_content_provider("text/event-stream",
  21955. [](size_t, DataSink &) { return false; });
  21956. });
  21957. Client client("localhost", get_port());
  21958. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21959. sse::SSEClient sse(client, "/header-check", headers);
  21960. sse.set_max_reconnect_attempts(1);
  21961. sse.start_async();
  21962. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21963. sse.stop();
  21964. EXPECT_TRUE(header_received.load());
  21965. }
  21966. // Test: Reconnect interval configuration
  21967. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21968. Client client("localhost", get_port());
  21969. sse::SSEClient sse(client, "/events");
  21970. auto &result = sse.set_reconnect_interval(500);
  21971. // Builder pattern should return reference to self
  21972. EXPECT_EQ(&result, &sse);
  21973. }
  21974. // Test: Max reconnect attempts
  21975. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21976. // Connect to non-existent port to force reconnects
  21977. Client client("localhost", 59998);
  21978. sse::SSEClient sse(client, "/events");
  21979. std::atomic<int> error_count{0};
  21980. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21981. sse.set_reconnect_interval(50);
  21982. sse.set_max_reconnect_attempts(2);
  21983. auto start = std::chrono::steady_clock::now();
  21984. sse.start(); // Blocking call
  21985. auto end = std::chrono::steady_clock::now();
  21986. // Should have stopped after 2 failed attempts
  21987. EXPECT_GE(error_count.load(), 2);
  21988. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21989. auto duration =
  21990. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21991. #ifdef _WIN32
  21992. // Windows is much slower for socket connection failures
  21993. EXPECT_LT(duration.count(), 7000);
  21994. #else
  21995. EXPECT_LT(duration.count(), 1000);
  21996. #endif
  21997. }
  21998. // Test: Multi-line data in integration
  21999. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22000. // Endpoint with multi-line data
  22001. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22002. res.set_chunked_content_provider(
  22003. "text/event-stream", [](size_t offset, DataSink &sink) {
  22004. if (offset == 0) {
  22005. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22006. sink.write(event.data(), event.size());
  22007. }
  22008. return false;
  22009. });
  22010. });
  22011. Client client("localhost", get_port());
  22012. sse::SSEClient sse(client, "/multiline-data");
  22013. std::string received_data;
  22014. std::mutex data_mutex;
  22015. sse.on_message([&](const sse::SSEMessage &msg) {
  22016. std::lock_guard<std::mutex> lock(data_mutex);
  22017. received_data = msg.data;
  22018. });
  22019. sse.set_reconnect_interval(100);
  22020. sse.set_max_reconnect_attempts(1);
  22021. sse.start_async();
  22022. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22023. sse.stop();
  22024. std::lock_guard<std::mutex> lock(data_mutex);
  22025. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22026. }
  22027. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22028. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22029. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22030. DataSink &sink) {
  22031. if (offset == 0) {
  22032. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22033. sink.write(events.data(), events.size());
  22034. }
  22035. return false;
  22036. });
  22037. });
  22038. Client client("localhost", get_port());
  22039. sse::SSEClient sse(client, "/empty-data-lines");
  22040. std::mutex mutex;
  22041. std::condition_variable cv;
  22042. std::vector<std::string> received;
  22043. sse.on_message([&](const sse::SSEMessage &msg) {
  22044. std::lock_guard<std::mutex> lock(mutex);
  22045. received.push_back(msg.data);
  22046. cv.notify_all();
  22047. });
  22048. sse.set_max_reconnect_attempts(1);
  22049. sse.start_async();
  22050. {
  22051. std::unique_lock<std::mutex> lock(mutex);
  22052. cv.wait_for(lock, std::chrono::seconds(2),
  22053. [&] { return received.size() >= 3; });
  22054. }
  22055. sse.stop();
  22056. ASSERT_GE(received.size(), 3u);
  22057. EXPECT_EQ(received[0], "");
  22058. EXPECT_EQ(received[1], "\nhello");
  22059. EXPECT_EQ(received[2], "");
  22060. }
  22061. // Test: Auto-reconnect after server disconnection
  22062. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22063. std::atomic<int> connection_count{0};
  22064. std::atomic<int> message_count{0};
  22065. // Endpoint that sends one event and closes, forcing reconnect
  22066. server_->Get("/reconnect-test",
  22067. [&connection_count](const Request &, Response &res) {
  22068. connection_count.fetch_add(1);
  22069. res.set_chunked_content_provider(
  22070. "text/event-stream", [](size_t offset, DataSink &sink) {
  22071. if (offset == 0) {
  22072. std::string event = "data: hello\n\n";
  22073. sink.write(event.data(), event.size());
  22074. }
  22075. return false; // Close connection after sending
  22076. });
  22077. });
  22078. Client client("localhost", get_port());
  22079. sse::SSEClient sse(client, "/reconnect-test");
  22080. sse.on_message([&message_count](const sse::SSEMessage &) {
  22081. message_count.fetch_add(1);
  22082. });
  22083. sse.set_reconnect_interval(100);
  22084. sse.set_max_reconnect_attempts(3);
  22085. sse.start_async();
  22086. // Wait long enough for multiple reconnects
  22087. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22088. sse.stop();
  22089. // Should have connected multiple times (initial + reconnects)
  22090. EXPECT_GE(connection_count.load(), 2);
  22091. // Should have received messages from multiple connections
  22092. EXPECT_GE(message_count.load(), 2);
  22093. }
  22094. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22095. std::atomic<int> connection_count{0};
  22096. // Neither Content-Length nor chunked: the close ends the stream
  22097. server_->Get("/close-delimited",
  22098. [&connection_count](const Request &, Response &res) {
  22099. connection_count.fetch_add(1);
  22100. res.set_content_provider(
  22101. "text/event-stream", [](size_t offset, DataSink &sink) {
  22102. if (offset == 0) {
  22103. std::string event = "data: hello\n\n";
  22104. sink.write(event.data(), event.size());
  22105. } else {
  22106. sink.done();
  22107. }
  22108. return true;
  22109. });
  22110. });
  22111. Client client("localhost", get_port());
  22112. sse::SSEClient sse(client, "/close-delimited");
  22113. std::atomic<int> error_count{0};
  22114. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22115. sse.set_reconnect_interval(100);
  22116. sse.start_async();
  22117. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22119. }
  22120. sse.stop();
  22121. // Reconnects as after any end of the stream, but reports no error
  22122. EXPECT_GE(connection_count.load(), 2);
  22123. EXPECT_EQ(0, error_count.load());
  22124. }
  22125. // Test: A retry field that is not all ASCII digits is ignored
  22126. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22127. std::atomic<int> connection_count{0};
  22128. server_->Get("/bad-retry",
  22129. [&connection_count](const Request &, Response &res) {
  22130. connection_count.fetch_add(1);
  22131. res.set_chunked_content_provider(
  22132. "text/event-stream", [](size_t offset, DataSink &sink) {
  22133. if (offset == 0) {
  22134. std::string event = "retry: -1\ndata: hello\n\n";
  22135. sink.write(event.data(), event.size());
  22136. }
  22137. return false;
  22138. });
  22139. });
  22140. Client client("localhost", get_port());
  22141. sse::SSEClient sse(client, "/bad-retry");
  22142. sse.set_reconnect_interval(10000);
  22143. sse.start_async();
  22144. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22145. sse.stop();
  22146. EXPECT_EQ(connection_count.load(), 1);
  22147. }
  22148. // Test: A retry field of all ASCII digits sets the reconnection time
  22149. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22150. std::mutex mutex;
  22151. std::condition_variable cv;
  22152. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22153. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22154. {
  22155. std::lock_guard<std::mutex> lock(mutex);
  22156. connected_at.push_back(std::chrono::steady_clock::now());
  22157. cv.notify_all();
  22158. }
  22159. res.set_chunked_content_provider(
  22160. "text/event-stream", [](size_t offset, DataSink &sink) {
  22161. if (offset == 0) {
  22162. std::string event = "retry: 0\ndata: hello\n\n";
  22163. sink.write(event.data(), event.size());
  22164. }
  22165. return false;
  22166. });
  22167. });
  22168. Client client("localhost", get_port());
  22169. sse::SSEClient sse(client, "/zero-retry");
  22170. sse.set_reconnect_interval(10000);
  22171. sse.start_async();
  22172. {
  22173. std::unique_lock<std::mutex> lock(mutex);
  22174. cv.wait_for(lock, std::chrono::seconds(5),
  22175. [&] { return connected_at.size() >= 2; });
  22176. }
  22177. sse.stop();
  22178. // The server-supplied interval is applied, but never below 100ms, so
  22179. // "retry: 0" does not cause a busy reconnect loop
  22180. std::lock_guard<std::mutex> lock(mutex);
  22181. ASSERT_GE(connected_at.size(), 2u);
  22182. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22183. connected_at[1] - connected_at[0])
  22184. .count();
  22185. EXPECT_GE(interval_ms, 100);
  22186. }
  22187. // Test: Last-Event-ID sent on reconnect
  22188. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22189. std::atomic<int> connection_count{0};
  22190. std::vector<std::string> received_last_event_ids;
  22191. std::mutex id_mutex;
  22192. // Endpoint that checks Last-Event-ID header and sends event with ID
  22193. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22194. int conn = connection_count.fetch_add(1);
  22195. // Capture the Last-Event-ID header from each connection
  22196. {
  22197. std::lock_guard<std::mutex> lock(id_mutex);
  22198. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22199. }
  22200. res.set_chunked_content_provider(
  22201. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22202. if (offset == 0) {
  22203. std::string event =
  22204. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22205. sink.write(event.data(), event.size());
  22206. }
  22207. return false;
  22208. });
  22209. });
  22210. Client client("localhost", get_port());
  22211. sse::SSEClient sse(client, "/reconnect-with-id");
  22212. sse.set_reconnect_interval(100);
  22213. sse.set_max_reconnect_attempts(3);
  22214. sse.start_async();
  22215. // Wait for at least 2 connections
  22216. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22217. sse.stop();
  22218. // Verify behavior
  22219. std::lock_guard<std::mutex> lock(id_mutex);
  22220. EXPECT_GE(received_last_event_ids.size(), 2u);
  22221. // First connection should have no Last-Event-ID
  22222. if (!received_last_event_ids.empty()) {
  22223. EXPECT_EQ(received_last_event_ids[0], "");
  22224. }
  22225. // Second connection should have Last-Event-ID from first connection
  22226. if (received_last_event_ids.size() >= 2) {
  22227. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22228. }
  22229. }
  22230. // Test: set_headers updates headers used on reconnect
  22231. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22232. std::vector<std::string> received_tokens;
  22233. std::mutex token_mutex;
  22234. // Endpoint that captures Authorization header
  22235. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22236. {
  22237. std::lock_guard<std::mutex> lock(token_mutex);
  22238. received_tokens.push_back(req.get_header_value("Authorization"));
  22239. }
  22240. res.set_chunked_content_provider(
  22241. "text/event-stream", [](size_t offset, DataSink &sink) {
  22242. if (offset == 0) {
  22243. std::string event = "data: hello\n\n";
  22244. sink.write(event.data(), event.size());
  22245. }
  22246. return false; // Close connection to trigger reconnect
  22247. });
  22248. });
  22249. Client client("localhost", get_port());
  22250. Headers headers = {{"Authorization", "Bearer old-token"}};
  22251. sse::SSEClient sse(client, "/auth-check", headers);
  22252. // Update headers on each successful connection
  22253. sse.on_open(
  22254. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22255. sse.set_reconnect_interval(100);
  22256. sse.set_max_reconnect_attempts(3);
  22257. sse.start_async();
  22258. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22259. sse.stop();
  22260. std::lock_guard<std::mutex> lock(token_mutex);
  22261. ASSERT_GE(received_tokens.size(), 2u);
  22262. // First connection uses original header
  22263. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22264. // Second connection uses updated header from set_headers
  22265. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22266. }
  22267. // Test: 401 allows reconnection (so on_error can refresh headers)
  22268. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22269. std::atomic<int> connection_count{0};
  22270. // Endpoint: returns 401 on first attempt, 200 on second
  22271. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22272. int conn = connection_count.fetch_add(1);
  22273. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22274. res.status = StatusCode::Unauthorized_401;
  22275. res.set_content("Unauthorized", "text/plain");
  22276. return;
  22277. }
  22278. res.set_chunked_content_provider(
  22279. "text/event-stream", [](size_t offset, DataSink &sink) {
  22280. if (offset == 0) {
  22281. std::string event = "data: authenticated\n\n";
  22282. sink.write(event.data(), event.size());
  22283. }
  22284. return false;
  22285. });
  22286. });
  22287. Client client("localhost", get_port());
  22288. Headers headers = {{"Authorization", "Bearer expired"}};
  22289. sse::SSEClient sse(client, "/auth-retry", headers);
  22290. std::atomic<bool> message_received{false};
  22291. // Refresh token on error
  22292. sse.on_error(
  22293. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22294. sse.on_message([&](const sse::SSEMessage &msg) {
  22295. if (msg.data == "authenticated") { message_received.store(true); }
  22296. });
  22297. sse.set_reconnect_interval(100);
  22298. sse.set_max_reconnect_attempts(3);
  22299. sse.start_async();
  22300. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22301. sse.stop();
  22302. // Should have reconnected after 401 and succeeded with new token
  22303. EXPECT_GE(connection_count.load(), 2);
  22304. EXPECT_TRUE(message_received.load());
  22305. }
  22306. TEST(Issue2318Test, EmptyHostString) {
  22307. {
  22308. httplib::Client cli_empty("", PORT);
  22309. auto res = cli_empty.Get("/");
  22310. ASSERT_FALSE(res);
  22311. EXPECT_EQ(httplib::Error::Connection, res.error());
  22312. }
  22313. {
  22314. httplib::Client cli(" ", PORT);
  22315. auto res = cli.Get("/");
  22316. ASSERT_FALSE(res);
  22317. EXPECT_EQ(httplib::Error::Connection, res.error());
  22318. }
  22319. }
  22320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22321. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22322. Server svr;
  22323. // Set a small payload limit (1KB)
  22324. svr.set_payload_max_length(1024);
  22325. svr.Post("/test", [&](const Request &req, Response &res) {
  22326. res.set_content("Body size: " + std::to_string(req.body.size()),
  22327. "text/plain");
  22328. });
  22329. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22330. auto se = detail::scope_exit([&] {
  22331. svr.stop();
  22332. listen_thread.join();
  22333. });
  22334. svr.wait_until_ready();
  22335. // Create data that compresses well but exceeds limit when decompressed
  22336. // 8KB of repeated null bytes compresses to a very small size
  22337. std::string original_data(8 * 1024, '\0');
  22338. // Compress the data using gzip
  22339. std::string compressed_data;
  22340. detail::gzip_compressor compressor;
  22341. compressor.compress(original_data.data(), original_data.size(), true,
  22342. [&](const char *data, size_t size) {
  22343. compressed_data.append(data, size);
  22344. return true;
  22345. });
  22346. // Verify compression worked (compressed should be much smaller)
  22347. ASSERT_LT(compressed_data.size(), original_data.size());
  22348. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22349. // Send compressed data with Content-Encoding: gzip
  22350. Client cli(HOST, PORT);
  22351. Headers headers = {{"Content-Encoding", "gzip"}};
  22352. auto res =
  22353. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22354. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22356. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22357. }
  22358. #endif
  22359. // ============================================================================
  22360. // OpenSSL-Specific Tests
  22361. // ============================================================================
  22362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22363. X509 *readCertificate(const std::string &strFileName) {
  22364. std::ifstream inStream(strFileName);
  22365. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22366. std::istreambuf_iterator<char>());
  22367. if (strCertPEM.empty()) return (nullptr);
  22368. BIO *pbCert = BIO_new(BIO_s_mem());
  22369. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22370. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22371. BIO_free(pbCert);
  22372. return (pCert);
  22373. }
  22374. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22375. std::ifstream inStream(strFileName);
  22376. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22377. std::istreambuf_iterator<char>());
  22378. if (strPrivateKeyPEM.empty()) return (nullptr);
  22379. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22380. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22381. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22382. BIO_free(pbPrivKey);
  22383. return (pPrivateKey);
  22384. }
  22385. TEST(BindServerTest, UpdateCerts) {
  22386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22387. int port = svr.bind_to_any_port("0.0.0.0");
  22388. ASSERT_TRUE(svr.is_valid());
  22389. ASSERT_TRUE(port > 0);
  22390. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22391. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22392. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22393. ASSERT_TRUE(cert != nullptr);
  22394. ASSERT_TRUE(ca_cert != nullptr);
  22395. ASSERT_TRUE(key != nullptr);
  22396. X509_STORE *cert_store = X509_STORE_new();
  22397. X509_STORE_add_cert(cert_store, ca_cert);
  22398. // svr.update_certs(cert, key, cert_store); // deprecated
  22399. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22400. CLIENT_CA_CERT_FILE);
  22401. ASSERT_TRUE(svr.is_valid());
  22402. svr.stop();
  22403. X509_STORE_free(cert_store);
  22404. X509_free(cert);
  22405. X509_free(ca_cert);
  22406. EVP_PKEY_free(key);
  22407. }
  22408. // Test that update_certs() updates client CA list correctly
  22409. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22410. // Start with file-based constructor
  22411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22412. ASSERT_TRUE(svr.is_valid());
  22413. // Initially no client CA list should be set
  22414. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22415. ASSERT_TRUE(ssl_ctx != nullptr);
  22416. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22417. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22418. // Now update with client CA (PEM string)
  22419. std::string cert_pem, key_pem, ca_pem;
  22420. read_file(SERVER_CERT_FILE, cert_pem);
  22421. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22422. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22423. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22424. ASSERT_TRUE(svr.is_valid());
  22425. // Now client CA list should be set
  22426. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22427. ASSERT_TRUE(ca_list_after != nullptr);
  22428. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22429. }
  22430. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22431. // Test that the file-path SSLServer constructor properly sets the client CA
  22432. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22434. ASSERT_TRUE(svr.is_valid());
  22435. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22436. ASSERT_TRUE(ssl_ctx != nullptr);
  22437. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22438. ASSERT_TRUE(ca_list != nullptr);
  22439. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22440. }
  22441. #endif
  22442. // ============================================================================
  22443. // MbedTLS-Specific Tests
  22444. // ============================================================================
  22445. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22446. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22447. using namespace httplib::tls;
  22448. // Track if callback was invoked
  22449. bool callback_invoked = false;
  22450. // The callback receives void* ctx which is actually MbedTlsContext*
  22451. // We can access the mbedtls_ssl_config via the context
  22452. auto setup_callback = [&callback_invoked](void *ctx) {
  22453. callback_invoked = true;
  22454. // Cast to MbedTlsContext* to access the ssl config
  22455. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22456. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22457. // Use static variables to hold certificate data (simplified for test)
  22458. static mbedtls_x509_crt own_cert;
  22459. static mbedtls_pk_context own_key;
  22460. static mbedtls_x509_crt ca_chain;
  22461. static bool initialized = false;
  22462. if (!initialized) {
  22463. mbedtls_x509_crt_init(&own_cert);
  22464. mbedtls_pk_init(&own_key);
  22465. mbedtls_x509_crt_init(&ca_chain);
  22466. // Load server certificate
  22467. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22468. return false;
  22469. }
  22470. // Load server private key.
  22471. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22472. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22473. #if MBEDTLS_VERSION_MAJOR == 3
  22474. ,
  22475. mbedtls_ctr_drbg_random, nullptr
  22476. #endif
  22477. ) != 0) {
  22478. return false;
  22479. }
  22480. // Load CA chain for client verification
  22481. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22482. return false;
  22483. }
  22484. initialized = true;
  22485. }
  22486. // Configure the SSL config
  22487. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22488. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22489. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22490. // Set minimum TLS version using mbedTLS native API
  22491. #if MBEDTLS_VERSION_MAJOR >= 3
  22492. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22493. #else
  22494. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22495. MBEDTLS_SSL_MINOR_VERSION_3);
  22496. #endif
  22497. return true;
  22498. };
  22499. SSLServer svr(setup_callback);
  22500. ASSERT_TRUE(svr.is_valid());
  22501. ASSERT_TRUE(callback_invoked);
  22502. svr.Get("/test", [&](const Request &req, Response &res) {
  22503. res.set_content("test", "text/plain");
  22504. auto cert = req.peer_cert();
  22505. ASSERT_TRUE(static_cast<bool>(cert));
  22506. auto common_name = cert.subject_cn();
  22507. EXPECT_EQ("Common Name", common_name);
  22508. });
  22509. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22510. auto se = detail::scope_exit([&] {
  22511. svr.stop();
  22512. t.join();
  22513. ASSERT_FALSE(svr.is_running());
  22514. });
  22515. svr.wait_until_ready();
  22516. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22517. cli.enable_server_certificate_verification(false);
  22518. cli.set_connection_timeout(30);
  22519. auto res = cli.Get("/test");
  22520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22521. ASSERT_EQ(StatusCode::OK_200, res->status);
  22522. }
  22523. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22524. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22525. // keep-alive SSL session, which reads through that config in
  22526. // mbedtls_ssl_close_notify.
  22527. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22528. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22529. ASSERT_TRUE(svr.is_valid());
  22530. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22531. res.set_content("test", "text/plain");
  22532. });
  22533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22534. auto se = detail::scope_exit([&] {
  22535. svr.stop();
  22536. t.join();
  22537. ASSERT_FALSE(svr.is_running());
  22538. });
  22539. svr.wait_until_ready();
  22540. {
  22541. SSLClient cli(HOST, PORT);
  22542. cli.enable_server_certificate_verification(false);
  22543. cli.set_keep_alive(true);
  22544. auto res = cli.Get("/test");
  22545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22546. ASSERT_EQ(StatusCode::OK_200, res->status);
  22547. // cli is destructed here with the keep-alive SSL session still open.
  22548. }
  22549. }
  22550. #endif
  22551. // WebSocket Tests
  22552. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22553. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22554. // defining the meaning of these bits has been negotiated.
  22555. auto make_frame = [](uint8_t first_byte) {
  22556. std::string frame;
  22557. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22558. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22559. frame += "Hello";
  22560. return frame;
  22561. };
  22562. // RSV1 set (0x40)
  22563. {
  22564. detail::BufferStream strm;
  22565. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22566. ws::Opcode opcode;
  22567. std::string payload;
  22568. bool fin;
  22569. EXPECT_EQ(
  22570. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22571. ws::impl::FrameRead::Fail);
  22572. }
  22573. // RSV2 set (0x20)
  22574. {
  22575. detail::BufferStream strm;
  22576. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22577. ws::Opcode opcode;
  22578. std::string payload;
  22579. bool fin;
  22580. EXPECT_EQ(
  22581. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22582. ws::impl::FrameRead::Fail);
  22583. }
  22584. // RSV3 set (0x10)
  22585. {
  22586. detail::BufferStream strm;
  22587. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22588. ws::Opcode opcode;
  22589. std::string payload;
  22590. bool fin;
  22591. EXPECT_EQ(
  22592. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22593. ws::impl::FrameRead::Fail);
  22594. }
  22595. // No RSV bits set - should succeed
  22596. {
  22597. detail::BufferStream strm;
  22598. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22599. ws::Opcode opcode;
  22600. std::string payload;
  22601. bool fin;
  22602. EXPECT_EQ(
  22603. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22604. ws::impl::FrameRead::Ok);
  22605. EXPECT_EQ(ws::Opcode::Text, opcode);
  22606. EXPECT_EQ("Hello", payload);
  22607. EXPECT_TRUE(fin);
  22608. }
  22609. }
  22610. TEST(WebSocketTest, ControlFrameValidation) {
  22611. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22612. // payload length <= 125.
  22613. // Ping with FIN=0 - must be rejected
  22614. {
  22615. detail::BufferStream strm;
  22616. std::string frame;
  22617. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22618. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22619. strm.write(frame.data(), frame.size());
  22620. ws::Opcode opcode;
  22621. std::string payload;
  22622. bool fin;
  22623. EXPECT_EQ(
  22624. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22625. ws::impl::FrameRead::Fail);
  22626. }
  22627. // Close with FIN=0 - must be rejected
  22628. {
  22629. detail::BufferStream strm;
  22630. std::string frame;
  22631. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22632. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22633. strm.write(frame.data(), frame.size());
  22634. ws::Opcode opcode;
  22635. std::string payload;
  22636. bool fin;
  22637. EXPECT_EQ(
  22638. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22639. ws::impl::FrameRead::Fail);
  22640. }
  22641. // Ping with payload_len=126 (extended length) - must be rejected
  22642. {
  22643. detail::BufferStream strm;
  22644. std::string frame;
  22645. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22646. frame += static_cast<char>(126); // payload_len=126 (>125)
  22647. frame += static_cast<char>(0x00); // extended length high byte
  22648. frame += static_cast<char>(126); // extended length low byte
  22649. frame += std::string(126, 'x');
  22650. strm.write(frame.data(), frame.size());
  22651. ws::Opcode opcode;
  22652. std::string payload;
  22653. bool fin;
  22654. EXPECT_EQ(
  22655. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22656. ws::impl::FrameRead::Fail);
  22657. }
  22658. // Ping with FIN=1 and payload_len=125 - should succeed
  22659. {
  22660. detail::BufferStream strm;
  22661. std::string frame;
  22662. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22663. frame += static_cast<char>(125); // payload_len=125
  22664. frame += std::string(125, 'x');
  22665. strm.write(frame.data(), frame.size());
  22666. ws::Opcode opcode;
  22667. std::string payload;
  22668. bool fin;
  22669. EXPECT_EQ(
  22670. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22671. ws::impl::FrameRead::Ok);
  22672. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22673. EXPECT_EQ(125u, payload.size());
  22674. EXPECT_TRUE(fin);
  22675. }
  22676. }
  22677. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22678. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22679. // length MUST be 0.
  22680. // MSB set - must be rejected
  22681. {
  22682. detail::BufferStream strm;
  22683. std::string frame;
  22684. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22685. frame += static_cast<char>(127); // 64-bit extended length
  22686. frame += static_cast<char>(0x80); // MSB set (invalid)
  22687. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22688. strm.write(frame.data(), frame.size());
  22689. ws::Opcode opcode;
  22690. std::string payload;
  22691. bool fin;
  22692. EXPECT_EQ(
  22693. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22694. ws::impl::FrameRead::Fail);
  22695. }
  22696. // MSB clear - should pass length parsing (will be rejected by max_len,
  22697. // but that's a different check; use a small length to verify)
  22698. {
  22699. detail::BufferStream strm;
  22700. std::string frame;
  22701. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22702. frame += static_cast<char>(127); // 64-bit extended length
  22703. frame += std::string(7, '\0'); // high bytes = 0
  22704. frame += static_cast<char>(0x03); // length = 3
  22705. frame += "abc";
  22706. strm.write(frame.data(), frame.size());
  22707. ws::Opcode opcode;
  22708. std::string payload;
  22709. bool fin;
  22710. EXPECT_EQ(
  22711. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22712. ws::impl::FrameRead::Ok);
  22713. EXPECT_EQ(ws::Opcode::Text, opcode);
  22714. EXPECT_EQ("abc", payload);
  22715. }
  22716. }
  22717. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22718. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22719. // Valid UTF-8
  22720. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22721. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22722. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22723. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22724. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22725. // Invalid UTF-8
  22726. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22727. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22728. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22729. EXPECT_FALSE(
  22730. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22731. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22732. }
  22733. TEST(WebSocketTest, ConnectAndDisconnect) {
  22734. Server svr;
  22735. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22736. std::string msg;
  22737. while (ws.read(msg)) {}
  22738. });
  22739. auto port = svr.bind_to_any_port(HOST);
  22740. std::thread t([&]() { svr.listen_after_bind(); });
  22741. svr.wait_until_ready();
  22742. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22743. auto res = client.connect();
  22744. ASSERT_TRUE(res);
  22745. EXPECT_EQ(Error::Success, res.error());
  22746. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22747. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22748. EXPECT_TRUE(client.is_open());
  22749. client.close();
  22750. EXPECT_FALSE(client.is_open());
  22751. svr.stop();
  22752. t.join();
  22753. }
  22754. TEST(WebSocketTest, ValidURL) {
  22755. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22756. EXPECT_TRUE(ws1.is_valid());
  22757. ws::WebSocketClient ws2("ws://example.com/path");
  22758. EXPECT_TRUE(ws2.is_valid());
  22759. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22760. EXPECT_TRUE(ws3.is_valid());
  22761. #ifdef CPPHTTPLIB_SSL_ENABLED
  22762. ws::WebSocketClient wss1("wss://example.com/path");
  22763. EXPECT_TRUE(wss1.is_valid());
  22764. ws::WebSocketClient wss2("wss://example.com:443/path");
  22765. EXPECT_TRUE(wss2.is_valid());
  22766. #endif
  22767. }
  22768. TEST(WebSocketTest, InvalidURL) {
  22769. // No scheme
  22770. ws::WebSocketClient ws1("localhost:8080/path");
  22771. EXPECT_FALSE(ws1.is_valid());
  22772. // No path
  22773. ws::WebSocketClient ws2("ws://localhost:8080");
  22774. EXPECT_FALSE(ws2.is_valid());
  22775. // Empty string
  22776. ws::WebSocketClient ws3("");
  22777. EXPECT_FALSE(ws3.is_valid());
  22778. // Missing host
  22779. ws::WebSocketClient ws4("ws://:8080/path");
  22780. EXPECT_FALSE(ws4.is_valid());
  22781. // Port number overflow — should not crash
  22782. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22783. EXPECT_FALSE(ws5.is_valid());
  22784. // Port out of range
  22785. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22786. EXPECT_FALSE(ws6.is_valid());
  22787. }
  22788. TEST(WebSocketTest, UnsupportedScheme) {
  22789. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22790. ws::WebSocketClient ws1("http://localhost:8080/path");
  22791. EXPECT_FALSE(ws1.is_valid());
  22792. ws::WebSocketClient ws2("https://localhost:8080/path");
  22793. EXPECT_FALSE(ws2.is_valid());
  22794. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22795. EXPECT_FALSE(ws3.is_valid());
  22796. #else
  22797. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22798. std::invalid_argument);
  22799. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22800. std::invalid_argument);
  22801. #endif
  22802. }
  22803. TEST(WebSocketTest, ConnectWhenInvalid) {
  22804. ws::WebSocketClient ws("not a valid url");
  22805. EXPECT_FALSE(ws.is_valid());
  22806. auto res = ws.connect();
  22807. EXPECT_FALSE(res);
  22808. EXPECT_EQ(Error::Connection, res.error());
  22809. EXPECT_EQ(-1, res.status());
  22810. }
  22811. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22812. // Grab a port that is free, then close it again so nothing listens there
  22813. Server svr;
  22814. auto port = svr.bind_to_any_port(HOST);
  22815. svr.stop();
  22816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22817. auto res = client.connect();
  22818. ASSERT_FALSE(res);
  22819. EXPECT_EQ(Error::Connection, res.error());
  22820. EXPECT_EQ(-1, res.status());
  22821. }
  22822. TEST(WebSocketTest, DefaultPort) {
  22823. ws::WebSocketClient ws1("ws://example.com/path");
  22824. EXPECT_TRUE(ws1.is_valid());
  22825. // ws:// defaults to port 80 (verified by successful parse)
  22826. #ifdef CPPHTTPLIB_SSL_ENABLED
  22827. ws::WebSocketClient ws2("wss://example.com/path");
  22828. EXPECT_TRUE(ws2.is_valid());
  22829. // wss:// defaults to port 443 (verified by successful parse)
  22830. #endif
  22831. }
  22832. TEST(WebSocketTest, IPv6LiteralAddress) {
  22833. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22834. EXPECT_TRUE(ws1.is_valid());
  22835. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22836. EXPECT_TRUE(ws2.is_valid());
  22837. }
  22838. TEST(WebSocketTest, ComplexPath) {
  22839. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22840. EXPECT_TRUE(ws1.is_valid());
  22841. ws::WebSocketClient ws2("ws://localhost:8080/");
  22842. EXPECT_TRUE(ws2.is_valid());
  22843. }
  22844. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22845. Server svr;
  22846. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22847. std::string msg;
  22848. while (ws.read(msg)) {}
  22849. });
  22850. auto port = svr.bind_to_any_port(HOST);
  22851. std::thread t([&]() { svr.listen_after_bind(); });
  22852. svr.wait_until_ready();
  22853. auto another_host = "example.com";
  22854. auto wrong_ip = "192.0.2.1";
  22855. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22856. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22857. ASSERT_TRUE(client.connect());
  22858. EXPECT_TRUE(client.is_open());
  22859. client.close();
  22860. svr.stop();
  22861. t.join();
  22862. }
  22863. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22864. Server svr;
  22865. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22866. std::string msg;
  22867. while (ws.read(msg)) {}
  22868. });
  22869. auto port = svr.bind_to_any_port(HOST);
  22870. std::thread t([&]() { svr.listen_after_bind(); });
  22871. svr.wait_until_ready();
  22872. auto wrong_ip = "192.0.2.1";
  22873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22874. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22875. client.set_connection_timeout(1);
  22876. client.set_read_timeout(1);
  22877. client.set_write_timeout(1);
  22878. EXPECT_FALSE(client.connect());
  22879. EXPECT_FALSE(client.is_open());
  22880. svr.stop();
  22881. t.join();
  22882. }
  22883. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22884. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22885. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22886. // (RFC 6761) is only a map key and the Host header value.
  22887. auto host = "target.invalid";
  22888. Server svr;
  22889. std::string received_host;
  22890. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22891. received_host = req.get_header_value("Host");
  22892. std::string msg;
  22893. while (ws.read(msg)) {}
  22894. });
  22895. auto port = svr.bind_to_any_port(HOST);
  22896. std::thread t([&]() { svr.listen_after_bind(); });
  22897. // ASSERT_* below returns from the test body, which would leave t joinable
  22898. // and make ~thread call std::terminate.
  22899. auto se = detail::scope_exit([&] {
  22900. svr.stop();
  22901. if (t.joinable()) { t.join(); }
  22902. });
  22903. svr.wait_until_ready();
  22904. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22905. std::to_string(port) + "/ws");
  22906. client.set_hostname_addr_map({{host, HOST}});
  22907. ASSERT_TRUE(client.connect());
  22908. EXPECT_TRUE(client.is_open());
  22909. client.close();
  22910. svr.stop();
  22911. t.join();
  22912. // The mapping only redirects the connection; the identity stays host_.
  22913. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22914. }
  22915. class WebSocketIntegrationTest : public ::testing::Test {
  22916. protected:
  22917. void SetUp() override {
  22918. server_ = httplib::detail::make_unique<Server>();
  22919. setup_server();
  22920. start_server();
  22921. }
  22922. void TearDown() override {
  22923. server_->stop();
  22924. if (server_thread_.joinable()) { server_thread_.join(); }
  22925. }
  22926. void setup_server() {
  22927. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22928. std::string msg;
  22929. ws::ReadResult ret;
  22930. while ((ret = ws.read(msg))) {
  22931. if (ret == ws::Binary) {
  22932. ws.send(msg.data(), msg.size());
  22933. } else {
  22934. ws.send(msg);
  22935. }
  22936. }
  22937. });
  22938. server_->WebSocket("/ws-echo-string",
  22939. [](const Request &, ws::WebSocket &ws) {
  22940. std::string msg;
  22941. while (ws.read(msg)) {
  22942. ws.send("echo: " + msg);
  22943. }
  22944. });
  22945. server_->WebSocket(
  22946. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22947. // Echo back request metadata
  22948. ws.send("path:" + req.path);
  22949. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22950. std::string msg;
  22951. while (ws.read(msg)) {}
  22952. });
  22953. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22954. std::string msg;
  22955. ws.read(msg); // wait for a message
  22956. ws.close();
  22957. });
  22958. server_->WebSocket("/ws-close-status",
  22959. [](const Request &, ws::WebSocket &ws) {
  22960. std::string msg;
  22961. ws.read(msg); // wait for a message
  22962. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22963. });
  22964. server_->WebSocket(
  22965. "/ws-subprotocol",
  22966. [](const Request &, ws::WebSocket &ws) {
  22967. std::string msg;
  22968. while (ws.read(msg)) {
  22969. ws.send(msg);
  22970. }
  22971. },
  22972. [](const std::vector<std::string> &protocols) -> std::string {
  22973. for (const auto &p : protocols) {
  22974. if (p == "graphql-ws") { return p; }
  22975. }
  22976. return "";
  22977. });
  22978. server_->WebSocket(
  22979. "/ws-subprotocol-unoffered",
  22980. [](const Request &, ws::WebSocket &ws) {
  22981. std::string msg;
  22982. while (ws.read(msg)) {
  22983. ws.send(msg);
  22984. }
  22985. },
  22986. [](const std::vector<std::string> &) -> std::string {
  22987. return "admin";
  22988. });
  22989. }
  22990. void start_server() {
  22991. port_ = server_->bind_to_any_port(HOST);
  22992. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22993. server_->wait_until_ready();
  22994. }
  22995. std::unique_ptr<Server> server_;
  22996. std::thread server_thread_;
  22997. int port_ = 0;
  22998. };
  22999. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23001. "/ws-echo");
  23002. ASSERT_TRUE(client.connect());
  23003. ASSERT_TRUE(client.is_open());
  23004. ASSERT_TRUE(client.send("Hello WebSocket"));
  23005. std::string msg;
  23006. EXPECT_EQ(ws::Text, client.read(msg));
  23007. EXPECT_EQ("Hello WebSocket", msg);
  23008. client.close();
  23009. }
  23010. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23011. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23012. "/ws-echo");
  23013. ASSERT_TRUE(client.connect());
  23014. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23015. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23016. std::string msg;
  23017. EXPECT_EQ(ws::Binary, client.read(msg));
  23018. EXPECT_EQ(binary_data, msg);
  23019. client.close();
  23020. }
  23021. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23023. "/ws-echo");
  23024. ASSERT_TRUE(client.connect());
  23025. for (int i = 0; i < 10; i++) {
  23026. auto text = "message " + std::to_string(i);
  23027. ASSERT_TRUE(client.send(text));
  23028. std::string msg;
  23029. ASSERT_TRUE(client.read(msg));
  23030. EXPECT_EQ(text, msg);
  23031. }
  23032. client.close();
  23033. }
  23034. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23035. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23036. "/ws-close");
  23037. ASSERT_TRUE(client.connect());
  23038. // Send a message to trigger the server to close
  23039. ASSERT_TRUE(client.send("trigger close"));
  23040. // The server will close, so read should return false
  23041. std::string msg;
  23042. EXPECT_FALSE(client.read(msg));
  23043. EXPECT_FALSE(client.is_open());
  23044. }
  23045. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23046. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23047. "/ws-echo");
  23048. ASSERT_TRUE(client.connect());
  23049. // 128KB message
  23050. std::string large_data(128 * 1024, 'X');
  23051. ASSERT_TRUE(client.send(large_data));
  23052. std::string msg;
  23053. ASSERT_TRUE(client.read(msg));
  23054. EXPECT_EQ(large_data, msg);
  23055. client.close();
  23056. }
  23057. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23059. "/ws-echo");
  23060. ASSERT_TRUE(client.connect());
  23061. const int num_threads = 4;
  23062. std::vector<std::thread> threads;
  23063. std::atomic<int> send_count{0};
  23064. for (int t = 0; t < num_threads; t++) {
  23065. threads.emplace_back([&client, &send_count, t]() {
  23066. for (int i = 0; i < 5; i++) {
  23067. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23068. if (client.send(text)) { send_count++; }
  23069. }
  23070. });
  23071. }
  23072. for (auto &th : threads) {
  23073. th.join();
  23074. }
  23075. int received = 0;
  23076. std::string msg;
  23077. while (received < send_count.load()) {
  23078. if (!client.read(msg)) { break; }
  23079. received++;
  23080. }
  23081. EXPECT_EQ(send_count.load(), received);
  23082. client.close();
  23083. }
  23084. TEST_F(WebSocketIntegrationTest, ReadString) {
  23085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23086. "/ws-echo-string");
  23087. ASSERT_TRUE(client.connect());
  23088. ASSERT_TRUE(client.send("hello"));
  23089. std::string msg;
  23090. ASSERT_TRUE(client.read(msg));
  23091. EXPECT_EQ("echo: hello", msg);
  23092. ASSERT_TRUE(client.send("world"));
  23093. ASSERT_TRUE(client.read(msg));
  23094. EXPECT_EQ("echo: world", msg);
  23095. client.close();
  23096. }
  23097. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23098. Headers headers = {{"X-Test-Header", "test-value"}};
  23099. ws::WebSocketClient client(
  23100. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23101. ASSERT_TRUE(client.connect());
  23102. std::string msg;
  23103. ASSERT_TRUE(client.read(msg));
  23104. EXPECT_EQ("path:/ws-request-info", msg);
  23105. ASSERT_TRUE(client.read(msg));
  23106. EXPECT_EQ("header:test-value", msg);
  23107. client.close();
  23108. }
  23109. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23111. "/ws-echo");
  23112. client.set_read_timeout(1, 0); // 1 second
  23113. ASSERT_TRUE(client.connect());
  23114. // Don't send anything — server echo handler waits for a message, so read()
  23115. // should time out. The connection survives it: nothing was consumed.
  23116. std::string msg;
  23117. EXPECT_EQ(client.read(msg), ws::Timeout);
  23118. EXPECT_TRUE(client.is_open());
  23119. // And it is still usable afterwards.
  23120. EXPECT_TRUE(client.send("after timeout"));
  23121. EXPECT_EQ(client.read(msg), ws::Text);
  23122. EXPECT_EQ(msg, "after timeout");
  23123. }
  23124. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23125. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23126. "/ws-echo");
  23127. client.set_read_timeout(1, 0);
  23128. ASSERT_TRUE(client.connect());
  23129. ASSERT_TRUE(client.send("first"));
  23130. std::string msg;
  23131. ASSERT_EQ(client.read(msg), ws::Text);
  23132. ASSERT_EQ(msg, "first");
  23133. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23134. // not be used with a read timeout: it would reprocess the previous message.
  23135. EXPECT_EQ(client.read(msg), ws::Timeout);
  23136. EXPECT_EQ(msg, "first");
  23137. }
  23138. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23140. "/ws-echo");
  23141. ASSERT_TRUE(client.connect());
  23142. // Setting it once the connection is open reaches the live stream, not just
  23143. // the seed for the next connect().
  23144. client.set_read_timeout(1, 0);
  23145. std::string msg;
  23146. EXPECT_EQ(client.read(msg), ws::Timeout);
  23147. EXPECT_TRUE(client.is_open());
  23148. }
  23149. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23151. "/ws-echo");
  23152. client.set_read_timeout(5, 0);
  23153. ASSERT_TRUE(client.connect());
  23154. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23155. // The server should reject it and close the connection.
  23156. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23157. client.send(oversized);
  23158. // The server's read() should have failed due to payload limit,
  23159. // so our read() should return false (connection closed).
  23160. std::string msg;
  23161. EXPECT_FALSE(client.read(msg));
  23162. }
  23163. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23164. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23165. "/ws-echo");
  23166. client.set_read_timeout(10, 0);
  23167. ASSERT_TRUE(client.connect());
  23168. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23169. // This should succeed.
  23170. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23171. ASSERT_TRUE(client.send(at_limit));
  23172. std::string msg;
  23173. ASSERT_TRUE(client.read(msg));
  23174. EXPECT_EQ(at_limit.size(), msg.size());
  23175. client.close();
  23176. }
  23177. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23178. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23179. "/nonexistent");
  23180. auto res = client.connect();
  23181. EXPECT_FALSE(res);
  23182. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23183. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23184. EXPECT_FALSE(client.is_open());
  23185. }
  23186. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23187. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23188. "/ws-echo");
  23189. ASSERT_TRUE(client.connect());
  23190. ASSERT_TRUE(client.send(""));
  23191. std::string msg;
  23192. EXPECT_EQ(ws::Text, client.read(msg));
  23193. EXPECT_EQ("", msg);
  23194. client.close();
  23195. }
  23196. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23198. "/ws-echo");
  23199. // First connection
  23200. ASSERT_TRUE(client.connect());
  23201. ASSERT_TRUE(client.send("first"));
  23202. std::string msg;
  23203. ASSERT_TRUE(client.read(msg));
  23204. EXPECT_EQ("first", msg);
  23205. client.close();
  23206. EXPECT_FALSE(client.is_open());
  23207. // Reconnect using the same client object
  23208. ASSERT_TRUE(client.connect());
  23209. ASSERT_TRUE(client.is_open());
  23210. ASSERT_TRUE(client.send("second"));
  23211. ASSERT_TRUE(client.read(msg));
  23212. EXPECT_EQ("second", msg);
  23213. client.close();
  23214. }
  23215. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23216. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23217. "/ws-close-status");
  23218. ASSERT_TRUE(client.connect());
  23219. // Trigger the server to close with GoingAway status
  23220. ASSERT_TRUE(client.send("trigger"));
  23221. // read() should return false after receiving the close frame
  23222. std::string msg;
  23223. EXPECT_FALSE(client.read(msg));
  23224. EXPECT_FALSE(client.is_open());
  23225. }
  23226. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23228. "/ws-echo");
  23229. ASSERT_TRUE(client.connect());
  23230. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23231. EXPECT_FALSE(client.is_open());
  23232. }
  23233. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23234. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23235. ws::WebSocketClient client(
  23236. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23237. ASSERT_TRUE(client.connect());
  23238. // Server should have selected graphql-ws
  23239. EXPECT_EQ("graphql-ws", client.subprotocol());
  23240. client.close();
  23241. }
  23242. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23243. Headers headers;
  23244. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23245. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23246. ws::WebSocketClient client(
  23247. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23248. ASSERT_TRUE(client.connect());
  23249. // The offer on the second field line counts too, so graphql-ws is selected
  23250. EXPECT_EQ("graphql-ws", client.subprotocol());
  23251. client.close();
  23252. }
  23253. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23254. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23255. ws::WebSocketClient client(
  23256. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23257. ASSERT_TRUE(client.connect());
  23258. // Server should not have selected any subprotocol
  23259. EXPECT_TRUE(client.subprotocol().empty());
  23260. client.close();
  23261. }
  23262. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23263. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23265. "/ws-subprotocol-unoffered",
  23266. headers);
  23267. ASSERT_TRUE(client.connect());
  23268. EXPECT_TRUE(client.subprotocol().empty());
  23269. client.close();
  23270. }
  23271. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23272. // Connect without requesting any subprotocol
  23273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23274. "/ws-subprotocol");
  23275. ASSERT_TRUE(client.connect());
  23276. EXPECT_TRUE(client.subprotocol().empty());
  23277. client.close();
  23278. }
  23279. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23281. "/ws-echo");
  23282. client.set_tcp_nodelay(true);
  23283. client.set_connection_timeout(3, 0);
  23284. bool socket_options_called = false;
  23285. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23286. ASSERT_TRUE(client.connect());
  23287. ASSERT_TRUE(client.is_open());
  23288. EXPECT_TRUE(socket_options_called);
  23289. ASSERT_TRUE(client.send("hello"));
  23290. std::string msg;
  23291. auto result = client.read(msg);
  23292. EXPECT_EQ(result, ws::ReadResult::Text);
  23293. EXPECT_EQ(msg, "hello");
  23294. client.close();
  23295. }
  23296. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23298. "/ws-echo");
  23299. client.set_connection_timeout(std::chrono::seconds(3));
  23300. client.set_write_timeout(std::chrono::seconds(3));
  23301. // A sub-second remainder exercises the seconds/microseconds split.
  23302. client.set_read_timeout(std::chrono::milliseconds(1500));
  23303. ASSERT_TRUE(client.connect());
  23304. auto start = std::chrono::steady_clock::now();
  23305. std::string msg;
  23306. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23307. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23308. std::chrono::steady_clock::now() - start)
  23309. .count();
  23310. // Above 1s so that dropping the microseconds half of the split fails here.
  23311. // Ignoring the setter altogether would not reach this line at all: a client
  23312. // waits forever by default.
  23313. EXPECT_GE(elapsed, 1400);
  23314. EXPECT_LT(elapsed, 30000);
  23315. }
  23316. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23317. Server svr;
  23318. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23319. if (!req.has_header("Authorization")) {
  23320. res.status = StatusCode::Unauthorized_401;
  23321. res.set_content("Unauthorized", "text/plain");
  23322. return Server::HandlerResponse::Handled;
  23323. }
  23324. return Server::HandlerResponse::Unhandled;
  23325. });
  23326. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23327. std::string msg;
  23328. while (ws.read(msg)) {
  23329. ws.send(msg);
  23330. }
  23331. });
  23332. auto port = svr.bind_to_any_port("localhost");
  23333. std::thread t([&]() { svr.listen_after_bind(); });
  23334. svr.wait_until_ready();
  23335. // Without Authorization header - should be rejected before upgrade
  23336. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23337. EXPECT_FALSE(client1.connect());
  23338. // The rejection is framed like any other HTTP response
  23339. {
  23340. Client cli("localhost", port);
  23341. Headers headers = {{"Upgrade", "websocket"},
  23342. {"Connection", "Upgrade"},
  23343. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23344. {"Sec-WebSocket-Version", "13"}};
  23345. auto res = cli.Get("/ws", headers);
  23346. ASSERT_TRUE(res);
  23347. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23348. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23349. EXPECT_EQ("Unauthorized", res->body);
  23350. }
  23351. // With Authorization header - should succeed
  23352. Headers headers = {{"Authorization", "Bearer token123"}};
  23353. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23354. headers);
  23355. ASSERT_TRUE(client2.connect());
  23356. ASSERT_TRUE(client2.send("hello"));
  23357. std::string msg;
  23358. ASSERT_TRUE(client2.read(msg));
  23359. EXPECT_EQ("hello", msg);
  23360. client2.close();
  23361. svr.stop();
  23362. t.join();
  23363. }
  23364. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23365. Server svr;
  23366. std::atomic<int> pre_routing_calls{0};
  23367. std::atomic<int> pre_request_calls{0};
  23368. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23369. pre_routing_calls++;
  23370. if (req.path == "/handled") {
  23371. res.set_content("handled", "text/plain");
  23372. return Server::HandlerResponse::Handled;
  23373. }
  23374. return Server::HandlerResponse::Unhandled;
  23375. });
  23376. svr.set_pre_request_handler([&](const Request &, Response &) {
  23377. pre_request_calls++;
  23378. return Server::HandlerResponse::Unhandled;
  23379. });
  23380. svr.Get("/http", [](const Request &, Response &res) {
  23381. res.set_content("http", "text/plain");
  23382. });
  23383. svr.WebSocket("/ws",
  23384. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23385. auto port = svr.bind_to_any_port("localhost");
  23386. std::thread t([&]() { svr.listen_after_bind(); });
  23387. auto se = detail::scope_exit([&] {
  23388. svr.stop();
  23389. t.join();
  23390. });
  23391. svr.wait_until_ready();
  23392. Headers upgrade = {{"Upgrade", "websocket"},
  23393. {"Connection", "Upgrade"},
  23394. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23395. {"Sec-WebSocket-Version", "13"}};
  23396. auto get = [&](const char *path) {
  23397. pre_routing_calls = 0;
  23398. return Client("localhost", port).Get(path, upgrade);
  23399. };
  23400. // No WebSocket route, but an HTTP one
  23401. auto res = get("/http");
  23402. ASSERT_TRUE(res);
  23403. EXPECT_EQ(StatusCode::OK_200, res->status);
  23404. EXPECT_EQ("http", res->body);
  23405. EXPECT_EQ(1, pre_routing_calls);
  23406. EXPECT_EQ(1, pre_request_calls);
  23407. // No route at all
  23408. res = get("/none");
  23409. ASSERT_TRUE(res);
  23410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23411. EXPECT_EQ(1, pre_routing_calls);
  23412. // Answered by the pre-routing handler
  23413. res = get("/handled");
  23414. ASSERT_TRUE(res);
  23415. EXPECT_EQ(StatusCode::OK_200, res->status);
  23416. EXPECT_EQ("handled", res->body);
  23417. EXPECT_EQ(1, pre_routing_calls);
  23418. // A WebSocket route
  23419. pre_routing_calls = 0;
  23420. pre_request_calls = 0;
  23421. {
  23422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23423. "/ws");
  23424. ASSERT_TRUE(client.connect());
  23425. std::string msg;
  23426. ASSERT_TRUE(client.read(msg));
  23427. EXPECT_EQ("ws", msg);
  23428. client.close();
  23429. }
  23430. EXPECT_EQ(1, pre_routing_calls);
  23431. EXPECT_EQ(1, pre_request_calls);
  23432. }
  23433. // An upgrade request answered by a hook leaves its body unread, so that body
  23434. // must not be served as the next request on the connection.
  23435. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23436. Server svr;
  23437. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23438. if (req.path == "/pre-routing") {
  23439. res.set_content("pre-routing", "text/plain");
  23440. return Server::HandlerResponse::Handled;
  23441. }
  23442. return Server::HandlerResponse::Unhandled;
  23443. });
  23444. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23445. if (req.matched_route == "/pre-request") {
  23446. res.set_content("pre-request", "text/plain");
  23447. return Server::HandlerResponse::Handled;
  23448. }
  23449. return Server::HandlerResponse::Unhandled;
  23450. });
  23451. svr.Get("/smuggled", [](const Request &, Response &res) {
  23452. res.set_content("smuggled", "text/plain");
  23453. });
  23454. svr.WebSocket("/pre-request",
  23455. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23456. auto port = svr.bind_to_any_port(HOST);
  23457. std::thread t([&]() { svr.listen_after_bind(); });
  23458. auto se = detail::scope_exit([&] {
  23459. svr.stop();
  23460. t.join();
  23461. });
  23462. svr.wait_until_ready();
  23463. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23464. for (auto path : {"/pre-routing", "/pre-request"}) {
  23465. std::string req = std::string("GET ") + path +
  23466. " HTTP/1.1\r\n"
  23467. "Host: localhost\r\n"
  23468. "Upgrade: websocket\r\n"
  23469. "Connection: Upgrade\r\n"
  23470. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23471. "Sec-WebSocket-Version: 13\r\n"
  23472. "Content-Length: " +
  23473. std::to_string(body.size()) + "\r\n\r\n" + body;
  23474. std::string res;
  23475. ASSERT_TRUE(send_request(5, req, &res, port));
  23476. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23477. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23478. // Only one response, and the body was not served as a request
  23479. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23480. }
  23481. }
  23482. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23483. Server svr;
  23484. std::atomic<int> pre_request_calls{0};
  23485. std::atomic<bool> route_matched{false};
  23486. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23487. pre_request_calls++;
  23488. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23489. if (req.get_header_value("Authorization") != "Bearer token123") {
  23490. res.status = StatusCode::Unauthorized_401;
  23491. res.set_content("Unauthorized", "text/plain");
  23492. return Server::HandlerResponse::Handled;
  23493. }
  23494. return Server::HandlerResponse::Unhandled;
  23495. });
  23496. std::atomic<bool> handler_called{false};
  23497. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23498. handler_called = true;
  23499. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23500. });
  23501. auto port = svr.bind_to_any_port("localhost");
  23502. std::thread t([&]() { svr.listen_after_bind(); });
  23503. svr.wait_until_ready();
  23504. // Without Authorization header - should be rejected before upgrade
  23505. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23506. "/ws/1");
  23507. EXPECT_FALSE(client1.connect());
  23508. EXPECT_FALSE(handler_called);
  23509. EXPECT_EQ(1, pre_request_calls);
  23510. EXPECT_TRUE(route_matched);
  23511. // The rejection is an ordinary HTTP response, not a protocol switch
  23512. {
  23513. Client cli("localhost", port);
  23514. Headers headers = {{"Upgrade", "websocket"},
  23515. {"Connection", "Upgrade"},
  23516. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23517. {"Sec-WebSocket-Version", "13"}};
  23518. auto res = cli.Get("/ws/1", headers);
  23519. ASSERT_TRUE(res);
  23520. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23521. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23522. EXPECT_EQ("Unauthorized", res->body);
  23523. }
  23524. EXPECT_FALSE(handler_called);
  23525. // With Authorization header - should succeed
  23526. Headers headers = {{"Authorization", "Bearer token123"}};
  23527. ws::WebSocketClient client2(
  23528. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23529. ASSERT_TRUE(client2.connect());
  23530. std::string msg;
  23531. ASSERT_TRUE(client2.read(msg));
  23532. EXPECT_EQ("/ws/:id 2", msg);
  23533. EXPECT_TRUE(handler_called);
  23534. client2.close();
  23535. svr.stop();
  23536. t.join();
  23537. }
  23538. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23539. Server svr;
  23540. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23541. // A read timeout is how a handler gets control back. Without it, a handler
  23542. // parked in read() can never write on the connection it is reading.
  23543. ws.set_read_timeout(std::chrono::milliseconds(100));
  23544. std::string msg;
  23545. while (ws.is_open()) {
  23546. auto r = ws.read(msg);
  23547. if (r == httplib::ws::Timeout) {
  23548. ws.send("tick");
  23549. continue;
  23550. }
  23551. if (r == httplib::ws::Fail) { break; }
  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. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23559. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23560. ASSERT_TRUE(client.connect());
  23561. // The client sends nothing, so anything it receives came out of the
  23562. // handler's timeout path.
  23563. std::string msg;
  23564. ASSERT_EQ(client.read(msg), ws::Text);
  23565. EXPECT_EQ("tick", msg);
  23566. client.close();
  23567. svr.stop();
  23568. t.join();
  23569. }
  23570. // Stream::read may return fewer bytes than asked for. This is that contract at
  23571. // its worst -- one byte per call -- which is what a frame header straddling a
  23572. // read buffer's boundary looks like to the frame parser.
  23573. class WsByteAtATimeStream : public Stream {
  23574. public:
  23575. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23576. bool is_readable() const override { return true; }
  23577. bool wait_readable() const override { return true; }
  23578. bool wait_writable() const override { return true; }
  23579. ssize_t read(char *ptr, size_t size) override {
  23580. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23581. *ptr = data_[pos_++];
  23582. return 1;
  23583. }
  23584. ssize_t write(const char *, size_t size) override {
  23585. return static_cast<ssize_t>(size);
  23586. }
  23587. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23588. ip = "127.0.0.1";
  23589. port = 0;
  23590. }
  23591. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23592. ip = "127.0.0.1";
  23593. port = 0;
  23594. }
  23595. socket_t socket() const override { return INVALID_SOCKET; }
  23596. time_t duration() const override { return 0; }
  23597. private:
  23598. std::string data_;
  23599. size_t pos_ = 0;
  23600. };
  23601. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23602. // The payload uses the 16-bit extended length, so the header, the length
  23603. // and the mask key are all multi-byte fields here. Each used to be read
  23604. // with a single read() call, which fails as soon as one is split. The
  23605. // payload is also a little over one read chunk, so it is read in two.
  23606. std::string body;
  23607. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23608. body += static_cast<char>(i % 251);
  23609. }
  23610. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23611. std::string frame;
  23612. frame += static_cast<char>(0x81); // FIN + Text
  23613. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23614. frame += static_cast<char>(body.size() >> 8);
  23615. frame += static_cast<char>(body.size() & 0xff);
  23616. for (size_t i = 0; i < 4; i++) {
  23617. frame += static_cast<char>(mask[i]);
  23618. }
  23619. for (size_t i = 0; i < body.size(); i++) {
  23620. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23621. }
  23622. WsByteAtATimeStream strm(frame);
  23623. ws::Opcode opcode;
  23624. std::string payload;
  23625. bool fin = false;
  23626. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23627. /*expect_masked=*/true, body.size()),
  23628. ws::impl::FrameRead::Ok);
  23629. EXPECT_TRUE(fin);
  23630. EXPECT_EQ(opcode, ws::Opcode::Text);
  23631. EXPECT_EQ(payload, body);
  23632. }
  23633. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23634. std::string body(2000, 'x');
  23635. std::string frame;
  23636. frame += static_cast<char>(0x82); // FIN + Binary
  23637. frame += static_cast<char>(126); // 16-bit length follows
  23638. frame += static_cast<char>(body.size() >> 8);
  23639. frame += static_cast<char>(body.size() & 0xff);
  23640. frame += body;
  23641. detail::BufferStream strm;
  23642. strm.write(frame.data(), frame.size());
  23643. ws::Opcode opcode;
  23644. std::string payload;
  23645. bool fin;
  23646. EXPECT_EQ(
  23647. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23648. ws::impl::FrameRead::Ok);
  23649. EXPECT_EQ(body, payload);
  23650. }
  23651. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23652. // The header announces the largest payload allowed, and only 3 bytes of it
  23653. // ever arrive.
  23654. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23655. std::string frame;
  23656. frame += static_cast<char>(0x82); // FIN + Binary
  23657. frame += static_cast<char>(127); // 64-bit length follows
  23658. for (int shift = 56; shift >= 0; shift -= 8) {
  23659. frame += static_cast<char>((len >> shift) & 0xff);
  23660. }
  23661. frame += "abc";
  23662. detail::BufferStream strm;
  23663. strm.write(frame.data(), frame.size());
  23664. ws::Opcode opcode;
  23665. std::string payload;
  23666. bool fin;
  23667. EXPECT_EQ(
  23668. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23669. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23670. ws::impl::FrameRead::Fail);
  23671. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23672. }
  23673. TEST(WebSocketTest, QueryStringInHandshake) {
  23674. Server svr;
  23675. std::mutex mtx;
  23676. std::string received_target;
  23677. std::string received_token;
  23678. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23679. {
  23680. std::lock_guard<std::mutex> lock(mtx);
  23681. received_target = req.target;
  23682. if (req.has_param("token")) {
  23683. received_token = req.get_param_value("token");
  23684. }
  23685. }
  23686. std::string msg;
  23687. while (ws.read(msg)) {
  23688. ws.send(msg);
  23689. }
  23690. });
  23691. auto port = svr.bind_to_any_port("localhost");
  23692. std::thread t([&]() { svr.listen_after_bind(); });
  23693. svr.wait_until_ready();
  23694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23695. "/ws?token=ABC&session=123");
  23696. ASSERT_TRUE(client.connect());
  23697. // Round-trip ensures the handler has run and captured the request.
  23698. ASSERT_TRUE(client.send("hello"));
  23699. std::string msg;
  23700. ASSERT_TRUE(client.read(msg));
  23701. EXPECT_EQ("hello", msg);
  23702. client.close();
  23703. {
  23704. std::lock_guard<std::mutex> lock(mtx);
  23705. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23706. EXPECT_EQ("ABC", received_token);
  23707. }
  23708. svr.stop();
  23709. t.join();
  23710. }
  23711. // Run a handshake against a throwaway server and hand the request the server
  23712. // received back to the caller, so tests can assert on the headers the client
  23713. // actually put on the wire.
  23714. static void capture_websocket_handshake_request(
  23715. const Headers &client_headers,
  23716. std::function<void(const Request &, int port)> verify) {
  23717. Server svr;
  23718. std::mutex mtx;
  23719. Request received;
  23720. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23721. {
  23722. std::lock_guard<std::mutex> lock(mtx);
  23723. received = req;
  23724. }
  23725. std::string msg;
  23726. while (ws.read(msg)) {
  23727. ws.send(msg);
  23728. }
  23729. });
  23730. auto port = svr.bind_to_any_port("localhost");
  23731. std::thread t([&]() { svr.listen_after_bind(); });
  23732. auto se = detail::scope_exit([&] {
  23733. svr.stop();
  23734. t.join();
  23735. });
  23736. svr.wait_until_ready();
  23737. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23738. client_headers);
  23739. ASSERT_TRUE(client.connect());
  23740. ASSERT_TRUE(client.send("hello"));
  23741. std::string msg;
  23742. ASSERT_TRUE(client.read(msg));
  23743. client.close();
  23744. {
  23745. std::lock_guard<std::mutex> lock(mtx);
  23746. verify(received, port);
  23747. }
  23748. }
  23749. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23750. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23751. // Non-default port must be present in the Host header. Default ports
  23752. // (80/443) are omitted; that logic is covered by
  23753. // MakeHostAndPortStringTest.
  23754. EXPECT_EQ("localhost:" + std::to_string(port),
  23755. req.get_header_value("Host"));
  23756. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23757. req.get_header_value("User-Agent"));
  23758. EXPECT_FALSE(req.has_header("Accept"));
  23759. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23760. EXPECT_FALSE(req.has_header("Content-Length"));
  23761. });
  23762. }
  23763. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23764. capture_websocket_handshake_request(
  23765. {{"Host", "example.com"},
  23766. {"User-Agent", "custom-agent"},
  23767. {"X-Custom", "value"}},
  23768. [](const Request &req, int) {
  23769. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23770. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23771. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23772. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23773. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23774. });
  23775. }
  23776. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23777. capture_websocket_handshake_request(
  23778. {{"Upgrade", "bogus"},
  23779. {"Connection", "close"},
  23780. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23781. {"Sec-WebSocket-Version", "8"}},
  23782. [](const Request &req, int) {
  23783. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23784. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23785. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23786. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23787. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23788. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23789. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23790. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23791. req.get_header_value("Sec-WebSocket-Key"));
  23792. });
  23793. }
  23794. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23795. // A header the client refuses to send must abort the handshake before any
  23796. // part of it reaches the wire; a lone request line would otherwise sit in
  23797. // the peer's buffer as a truncated request.
  23798. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23799. ASSERT_NE(INVALID_SOCKET, srv);
  23800. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23801. sockaddr_in addr{};
  23802. addr.sin_family = AF_INET;
  23803. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23804. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23805. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23806. ASSERT_EQ(0, ::listen(srv, 1));
  23807. sockaddr_in bound{};
  23808. socklen_t bound_len = sizeof(bound);
  23809. ASSERT_EQ(
  23810. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23811. auto port = ntohs(bound.sin_port);
  23812. ssize_t received = -1;
  23813. std::thread t([&] {
  23814. // Bound every blocking call so a regression fails the test with a bad
  23815. // value instead of hanging the suite.
  23816. fd_set rfds;
  23817. FD_ZERO(&rfds);
  23818. FD_SET(srv, &rfds);
  23819. timeval tv{5, 0};
  23820. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23821. 0) {
  23822. return;
  23823. }
  23824. sockaddr_in cli_addr{};
  23825. socklen_t cli_len = sizeof(cli_addr);
  23826. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23827. if (cli == INVALID_SOCKET) { return; }
  23828. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23829. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23830. char buf[4096];
  23831. received = ::recv(cli, buf, sizeof(buf), 0);
  23832. });
  23833. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23834. // connect() has already shut the socket down by the time it returns false,
  23835. // so the peer sees EOF without waiting for the client to be destroyed.
  23836. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23837. {{"X-Bad", "a\r\nInjected: 1"}});
  23838. EXPECT_FALSE(client.connect());
  23839. t.join();
  23840. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23841. EXPECT_EQ(0, received);
  23842. }
  23843. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23844. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23845. // contains "upgrade" as a substring is a different token and must not
  23846. // start a WebSocket handshake.
  23847. auto make_request = [](const std::vector<std::string> &connection_values) {
  23848. Request req;
  23849. req.method = "GET";
  23850. req.headers.emplace("Upgrade", "websocket");
  23851. for (const auto &value : connection_values) {
  23852. req.headers.emplace("Connection", value);
  23853. }
  23854. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23855. req.headers.emplace("Sec-WebSocket-Version", "13");
  23856. return req;
  23857. };
  23858. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23859. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23860. EXPECT_TRUE(
  23861. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23862. EXPECT_TRUE(
  23863. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23864. EXPECT_TRUE(
  23865. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23866. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23867. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23868. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23869. EXPECT_FALSE(
  23870. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23871. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23872. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23873. }
  23874. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23875. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23876. // asks recipients to match each protocol-name case-insensitively, and RFC
  23877. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23878. // client naming websocket alongside another protocol, or on a second field
  23879. // line, is offering websocket; a value that merely contains "websocket" as a
  23880. // substring is a different protocol name and is not.
  23881. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23882. Request req;
  23883. req.method = "GET";
  23884. for (const auto &value : upgrade_values) {
  23885. req.headers.emplace("Upgrade", value);
  23886. }
  23887. req.headers.emplace("Connection", "Upgrade");
  23888. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23889. req.headers.emplace("Sec-WebSocket-Version", "13");
  23890. return req;
  23891. };
  23892. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23893. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23894. EXPECT_TRUE(
  23895. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23896. EXPECT_TRUE(
  23897. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23898. EXPECT_TRUE(
  23899. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23900. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23901. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23902. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23903. EXPECT_FALSE(
  23904. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23905. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23906. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23907. }
  23908. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23909. Server svr;
  23910. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23911. auto port = svr.bind_to_any_port("localhost");
  23912. std::thread t([&]() { svr.listen_after_bind(); });
  23913. auto se = detail::scope_exit([&] {
  23914. svr.stop();
  23915. t.join();
  23916. });
  23917. svr.wait_until_ready();
  23918. Headers headers = {{"Upgrade", "websocket"},
  23919. {"Connection", "notupgrade"},
  23920. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23921. {"Sec-WebSocket-Version", "13"}};
  23922. Client cli("localhost", port);
  23923. auto res = cli.Get("/ws", headers);
  23924. // The route exists only as a WebSocket route, so a request that fails the
  23925. // handshake check falls through to ordinary routing.
  23926. ASSERT_TRUE(res);
  23927. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23928. }
  23929. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23930. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23931. // Connection value is the only thing left for the client to reject.
  23932. Server svr;
  23933. svr.Get("/ws", [](const Request &req, Response &res) {
  23934. res.status = StatusCode::SwitchingProtocol_101;
  23935. res.set_header("Upgrade", "websocket");
  23936. res.set_header("Connection", "notupgrade");
  23937. res.set_header("Sec-WebSocket-Accept",
  23938. detail::websocket_accept_key(
  23939. req.get_header_value("Sec-WebSocket-Key")));
  23940. });
  23941. auto port = svr.bind_to_any_port("localhost");
  23942. std::thread t([&]() { svr.listen_after_bind(); });
  23943. auto se = detail::scope_exit([&] {
  23944. svr.stop();
  23945. t.join();
  23946. });
  23947. svr.wait_until_ready();
  23948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23949. auto res = client.connect();
  23950. EXPECT_FALSE(res);
  23951. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23952. EXPECT_FALSE(client.is_open());
  23953. }
  23954. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23955. Server svr;
  23956. svr.Get("/ws", [](const Request &req, Response &res) {
  23957. res.status = StatusCode::SwitchingProtocol_101;
  23958. res.set_header("Upgrade", "websocket");
  23959. res.set_header("Connection", "Upgrade");
  23960. res.set_header("Sec-WebSocket-Accept",
  23961. detail::websocket_accept_key(
  23962. req.get_header_value("Sec-WebSocket-Key")));
  23963. res.set_header("Sec-WebSocket-Protocol", "admin");
  23964. });
  23965. auto port = svr.bind_to_any_port("localhost");
  23966. std::thread t([&]() { svr.listen_after_bind(); });
  23967. auto se = detail::scope_exit([&] {
  23968. svr.stop();
  23969. t.join();
  23970. });
  23971. svr.wait_until_ready();
  23972. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23973. // Server selects a subprotocol the client never offered
  23974. {
  23975. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23976. ws::WebSocketClient client(url, headers);
  23977. auto res = client.connect();
  23978. EXPECT_FALSE(res);
  23979. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23980. EXPECT_FALSE(client.is_open());
  23981. EXPECT_TRUE(client.subprotocol().empty());
  23982. }
  23983. // Client offered none but the server named one anyway
  23984. {
  23985. ws::WebSocketClient client(url);
  23986. auto res = client.connect();
  23987. EXPECT_FALSE(res);
  23988. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23989. EXPECT_FALSE(client.is_open());
  23990. EXPECT_TRUE(client.subprotocol().empty());
  23991. }
  23992. }
  23993. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23994. // The socket path doubles as the URL host, so it must not contain '/'.
  23995. const char *shard = getenv("GTEST_SHARD_INDEX");
  23996. const std::string sock_path =
  23997. shard ? std::string("httplib-ws-") + shard + ".sock"
  23998. : std::string("httplib-ws.sock");
  23999. std::remove(sock_path.c_str());
  24000. Server svr;
  24001. std::mutex mtx;
  24002. std::string received_host;
  24003. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24004. {
  24005. std::lock_guard<std::mutex> lock(mtx);
  24006. received_host = req.get_header_value("Host");
  24007. }
  24008. std::string msg;
  24009. while (ws.read(msg)) {
  24010. ws.send(msg);
  24011. }
  24012. });
  24013. svr.set_address_family(AF_UNIX);
  24014. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24015. auto se = detail::scope_exit([&] {
  24016. svr.stop();
  24017. t.join();
  24018. std::remove(sock_path.c_str());
  24019. });
  24020. svr.wait_until_ready();
  24021. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24022. client.set_address_family(AF_UNIX);
  24023. ASSERT_TRUE(client.connect());
  24024. ASSERT_TRUE(client.send("hello"));
  24025. std::string msg;
  24026. ASSERT_TRUE(client.read(msg));
  24027. client.close();
  24028. {
  24029. std::lock_guard<std::mutex> lock(mtx);
  24030. // There is no host:port for a Unix socket, so the same "localhost"
  24031. // placeholder the HTTP client uses is expected.
  24032. EXPECT_EQ("localhost", received_host);
  24033. }
  24034. }
  24035. // Two threads must never parse WebSocket frames from the same stream.
  24036. // close() used to read the peer's Close reply with its own frame read, so it
  24037. // raced a reader thread that was in the middle of a payload: the payload loop
  24038. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24039. // so bytes taken by close() were replaced with bytes from further along the
  24040. // stream. The message kept its length and silently changed content.
  24041. //
  24042. // The raw peer below sends a frame header plus part of the payload, waits for
  24043. // the handler to call close(), and only then sends the rest. Whichever thread
  24044. // would win the race for those bytes, the message must arrive intact, because
  24045. // close() must not touch the stream while read() owns it.
  24046. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24047. #ifndef _WIN32
  24048. signal(SIGPIPE, SIG_IGN);
  24049. #endif
  24050. const size_t payload_len = 120; // fits the 7-bit length field
  24051. const size_t prefix_len = 8;
  24052. const int attempts = 8;
  24053. std::string expected(payload_len, '\0');
  24054. for (size_t i = 0; i < payload_len; i++) {
  24055. expected[i] = static_cast<char>('a' + i % 26);
  24056. }
  24057. std::atomic<bool> peer_stalled{false};
  24058. std::atomic<bool> handler_done{false};
  24059. std::mutex received_mutex;
  24060. std::vector<std::string> received;
  24061. // Bound every wait, so a regression fails the test instead of hanging the
  24062. // suite.
  24063. auto wait_for = [](const std::atomic<bool> &flag) {
  24064. for (int i = 0; i < 500 && !flag; i++) {
  24065. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24066. }
  24067. };
  24068. Server svr;
  24069. svr.set_websocket_ping_interval(0);
  24070. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24071. std::thread reader([&]() {
  24072. std::string msg;
  24073. while (ws.read(msg)) {
  24074. std::lock_guard<std::mutex> guard(received_mutex);
  24075. received.push_back(msg);
  24076. }
  24077. });
  24078. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24079. // inside read_websocket_frame() when close() runs.
  24080. wait_for(peer_stalled);
  24081. ws.close();
  24082. reader.join();
  24083. handler_done = true;
  24084. });
  24085. auto port = svr.bind_to_any_port("127.0.0.1");
  24086. std::thread t([&]() { svr.listen_after_bind(); });
  24087. auto se = detail::scope_exit([&] {
  24088. svr.stop();
  24089. t.join();
  24090. });
  24091. svr.wait_until_ready();
  24092. auto send_bytes = [](socket_t s, const std::string &data) {
  24093. #ifdef _WIN32
  24094. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24095. #else
  24096. auto n = ::send(s, data.data(), data.size(), 0);
  24097. #endif
  24098. return n == static_cast<decltype(n)>(data.size());
  24099. };
  24100. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24101. // Every length used here fits the 7-bit length field.
  24102. auto masked_header = [](uint8_t first_byte, size_t len) {
  24103. std::string h;
  24104. h += static_cast<char>(first_byte);
  24105. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24106. h.append(4, '\0'); // mask key
  24107. return h;
  24108. };
  24109. for (int attempt = 0; attempt < attempts; attempt++) {
  24110. peer_stalled = false;
  24111. handler_done = false;
  24112. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24113. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24114. auto se_sock = detail::scope_exit([&] {
  24115. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24116. });
  24117. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24118. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24119. sockaddr_in addr{};
  24120. addr.sin_family = AF_INET;
  24121. addr.sin_port = htons(static_cast<uint16_t>(port));
  24122. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24123. ASSERT_EQ(
  24124. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24125. << "attempt " << attempt;
  24126. ASSERT_TRUE(send_bytes(sock,
  24127. "GET /ws HTTP/1.1\r\n"
  24128. "Host: 127.0.0.1\r\n"
  24129. "Upgrade: websocket\r\n"
  24130. "Connection: Upgrade\r\n"
  24131. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24132. "Sec-WebSocket-Version: 13\r\n"
  24133. "\r\n"))
  24134. << "attempt " << attempt;
  24135. std::string response;
  24136. while (response.find("\r\n\r\n") == std::string::npos) {
  24137. char buf[512];
  24138. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24139. if (n <= 0) { break; }
  24140. response.append(buf, static_cast<size_t>(n));
  24141. }
  24142. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24143. << "attempt " << attempt;
  24144. // Send the header of a Binary message but only the first prefix_len bytes
  24145. // of its payload, leaving the reader thread stalled inside the payload.
  24146. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24147. expected.substr(0, prefix_len)))
  24148. << "attempt " << attempt;
  24149. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24150. peer_stalled = true;
  24151. // Let close() send its Close frame and park in its own read before the
  24152. // rest of the payload arrives, so both threads are waiting for it.
  24153. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24154. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24155. close_frame += static_cast<char>(0x03); // status 1000
  24156. close_frame += static_cast<char>(0xE8);
  24157. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24158. << "attempt " << attempt;
  24159. // Closing the peer releases the reader thread even on the buggy path,
  24160. // where it waits for bytes another thread already consumed.
  24161. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24162. detail::close_socket(sock);
  24163. sock = INVALID_SOCKET;
  24164. wait_for(handler_done);
  24165. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24166. }
  24167. std::lock_guard<std::mutex> guard(received_mutex);
  24168. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24169. << "a message in flight when close() ran was dropped";
  24170. for (size_t i = 0; i < received.size(); i++) {
  24171. EXPECT_EQ(expected, received[i]) << "message " << i;
  24172. }
  24173. }
  24174. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24175. // returning the socket, or INVALID_SOCKET.
  24176. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24177. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24178. if (sock == INVALID_SOCKET) { return sock; }
  24179. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24180. sockaddr_in addr{};
  24181. addr.sin_family = AF_INET;
  24182. addr.sin_port = htons(static_cast<uint16_t>(port));
  24183. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24184. std::string req = "GET " + path +
  24185. " HTTP/1.1\r\n"
  24186. "Host: 127.0.0.1\r\n"
  24187. "Upgrade: websocket\r\n"
  24188. "Connection: Upgrade\r\n"
  24189. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24190. "Sec-WebSocket-Version: 13\r\n"
  24191. "\r\n";
  24192. std::string res;
  24193. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24194. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24195. static_cast<ssize_t>(req.size())) {
  24196. char c;
  24197. while (res.find("\r\n\r\n") == std::string::npos &&
  24198. ::recv(sock, &c, 1, 0) == 1) {
  24199. res += c;
  24200. }
  24201. }
  24202. if (res.find(" 101 ") == std::string::npos) {
  24203. detail::close_socket(sock);
  24204. return INVALID_SOCKET;
  24205. }
  24206. return sock;
  24207. }
  24208. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24209. // The payload must fit the 7-bit length field.
  24210. static std::string masked_frame(uint8_t first_byte,
  24211. const std::string &payload) {
  24212. std::string f;
  24213. f += static_cast<char>(first_byte);
  24214. f += static_cast<char>(0x80 | payload.size());
  24215. f.append(4, '\0');
  24216. return f + payload;
  24217. }
  24218. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24219. std::atomic<bool> done{false};
  24220. std::string received;
  24221. Server svr;
  24222. svr.set_websocket_ping_interval(0);
  24223. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24224. std::string msg;
  24225. if (ws.read(msg) == ws::Binary) { received = msg; }
  24226. done = true;
  24227. });
  24228. auto port = svr.bind_to_any_port("127.0.0.1");
  24229. std::thread t([&]() { svr.listen_after_bind(); });
  24230. auto se = detail::scope_exit([&] {
  24231. svr.stop();
  24232. t.join();
  24233. });
  24234. svr.wait_until_ready();
  24235. auto sock = connect_raw_websocket(port, "/ws");
  24236. ASSERT_NE(INVALID_SOCKET, sock);
  24237. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24238. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24239. masked_frame(0x89, "p") + // FIN + Ping
  24240. masked_frame(0x80, "lo"); // FIN + Continuation
  24241. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24242. for (int i = 0; i < 500 && !done; i++) {
  24243. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24244. }
  24245. ASSERT_TRUE(done);
  24246. EXPECT_EQ("Hello", received);
  24247. // The Ping between the fragments is answered with a Pong.
  24248. char pong[3];
  24249. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24250. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24251. }
  24252. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24253. Server svr;
  24254. svr.set_websocket_ping_interval(-1);
  24255. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24256. std::string msg;
  24257. while (ws.read(msg)) {}
  24258. });
  24259. auto port = svr.bind_to_any_port("127.0.0.1");
  24260. std::thread t([&]() { svr.listen_after_bind(); });
  24261. auto se = detail::scope_exit([&] {
  24262. svr.stop();
  24263. t.join();
  24264. });
  24265. svr.wait_until_ready();
  24266. auto sock = connect_raw_websocket(port, "/ws");
  24267. ASSERT_NE(INVALID_SOCKET, sock);
  24268. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24269. // Nothing comes while the client stays quiet.
  24270. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24271. char c;
  24272. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24273. }
  24274. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24275. // and that has to end a read() already waiting on the peer, on every platform.
  24276. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24277. // The peer sends no pings, and its handler never calls read(), which is
  24278. // where pongs are written.
  24279. std::mutex mutex;
  24280. std::condition_variable cv;
  24281. auto release = false;
  24282. svr.set_websocket_ping_interval(0);
  24283. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24284. std::unique_lock<std::mutex> lock(mutex);
  24285. cv.wait(lock, [&] { return release; });
  24286. });
  24287. auto port = svr.bind_to_any_port(HOST);
  24288. std::thread t([&]() { svr.listen_after_bind(); });
  24289. auto se = detail::scope_exit([&] {
  24290. {
  24291. std::lock_guard<std::mutex> lock(mutex);
  24292. release = true;
  24293. }
  24294. cv.notify_all();
  24295. svr.stop();
  24296. t.join();
  24297. });
  24298. svr.wait_until_ready();
  24299. ws::WebSocketClient client(std::string(scheme) +
  24300. "://localhost:" + std::to_string(port) + "/ws");
  24301. #ifdef CPPHTTPLIB_SSL_ENABLED
  24302. client.enable_server_certificate_verification(false);
  24303. #endif
  24304. // A ping a second, given up on after two go unanswered: about 3s
  24305. client.set_websocket_ping_interval(1);
  24306. client.set_websocket_max_missed_pongs(2);
  24307. // Well past that, so that a read the timeout ends instead stands out
  24308. client.set_read_timeout(10);
  24309. ASSERT_TRUE(client.connect());
  24310. auto start = std::chrono::steady_clock::now();
  24311. std::string msg;
  24312. EXPECT_EQ(ws::Fail, client.read(msg));
  24313. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24314. std::chrono::steady_clock::now() - start)
  24315. .count(),
  24316. 6000);
  24317. EXPECT_FALSE(client.is_open());
  24318. }
  24319. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24320. Server svr;
  24321. check_pong_timeout_ends_read(svr, "ws");
  24322. }
  24323. #ifdef CPPHTTPLIB_SSL_ENABLED
  24324. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24326. ASSERT_TRUE(svr.is_valid());
  24327. check_pong_timeout_ends_read(svr, "wss");
  24328. }
  24329. #endif
  24330. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24331. Server svr;
  24332. svr.set_websocket_ping_interval(0);
  24333. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24334. std::string msg;
  24335. while (ws.read(msg)) {}
  24336. });
  24337. auto port = svr.bind_to_any_port("127.0.0.1");
  24338. std::thread t([&]() { svr.listen_after_bind(); });
  24339. auto se = detail::scope_exit([&] {
  24340. svr.stop();
  24341. t.join();
  24342. });
  24343. svr.wait_until_ready();
  24344. // Each Close payload and the reply it should get: an echo when valid, 1002
  24345. // otherwise.
  24346. std::vector<std::pair<std::string, std::string>> cases = {
  24347. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24348. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24349. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24350. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24351. };
  24352. // Also between the fragments of a message.
  24353. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24354. for (const auto &c : cases) {
  24355. auto sock = connect_raw_websocket(port, "/ws");
  24356. ASSERT_NE(INVALID_SOCKET, sock);
  24357. auto frames = prefix + masked_frame(0x88, c.first);
  24358. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24359. std::string reply;
  24360. char buf[256];
  24361. while (reply.size() < 2 + c.second.size()) {
  24362. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24363. if (n <= 0) { break; }
  24364. reply.append(buf, static_cast<size_t>(n));
  24365. }
  24366. detail::close_socket(sock);
  24367. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24368. c.second,
  24369. reply);
  24370. }
  24371. }
  24372. }
  24373. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24374. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24375. protected:
  24376. void SetUp() override {
  24377. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24378. SERVER_PRIVATE_KEY_FILE);
  24379. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24380. std::string msg;
  24381. ws::ReadResult ret;
  24382. while ((ret = ws.read(msg))) {
  24383. if (ret == ws::Binary) {
  24384. ws.send(msg.data(), msg.size());
  24385. } else {
  24386. ws.send(msg);
  24387. }
  24388. }
  24389. });
  24390. port_ = server_->bind_to_any_port(HOST);
  24391. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24392. server_->wait_until_ready();
  24393. }
  24394. void TearDown() override {
  24395. server_->stop();
  24396. if (server_thread_.joinable()) { server_thread_.join(); }
  24397. }
  24398. std::unique_ptr<SSLServer> server_;
  24399. std::thread server_thread_;
  24400. int port_ = 0;
  24401. };
  24402. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24403. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24404. {
  24405. ws::WebSocketClient client(url);
  24406. client.enable_server_certificate_verification(false);
  24407. auto calls = 0;
  24408. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24409. calls++;
  24410. return false;
  24411. });
  24412. EXPECT_FALSE(client.connect());
  24413. EXPECT_GT(calls, 0);
  24414. }
  24415. {
  24416. ws::WebSocketClient client(url);
  24417. client.enable_server_certificate_verification(false);
  24418. client.set_session_verifier([](tls::session_t) {
  24419. return SSLVerifierResponse::CertificateRejected;
  24420. });
  24421. EXPECT_FALSE(client.connect());
  24422. }
  24423. {
  24424. ws::WebSocketClient client(url);
  24425. client.enable_server_certificate_verification(false);
  24426. client.set_session_verifier([](tls::session_t) {
  24427. return SSLVerifierResponse::CertificateAccepted;
  24428. });
  24429. EXPECT_TRUE(client.connect());
  24430. }
  24431. }
  24432. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24433. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24434. "/ws-echo");
  24435. client.enable_server_certificate_verification(false);
  24436. ASSERT_TRUE(client.connect());
  24437. ASSERT_TRUE(client.is_open());
  24438. ASSERT_TRUE(client.send("Hello WSS"));
  24439. std::string msg;
  24440. EXPECT_EQ(ws::Text, client.read(msg));
  24441. EXPECT_EQ("Hello WSS", msg);
  24442. client.close();
  24443. }
  24444. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24445. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24446. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24447. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24448. // client (without calling close() first) is the only path that runs
  24449. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24450. // bug exactly.
  24451. //
  24452. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24453. // when linked against an instrumented libssl; run under Valgrind to catch it
  24454. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24455. // suite (the freed session otherwise stalls on the close handshake) — this test
  24456. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24457. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24458. {
  24459. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24460. "/ws-echo");
  24461. client.enable_server_certificate_verification(false);
  24462. client.set_read_timeout(2, 0);
  24463. client.set_write_timeout(2, 0);
  24464. ASSERT_TRUE(client.connect());
  24465. ASSERT_TRUE(client.is_open());
  24466. ASSERT_TRUE(client.send("still open"));
  24467. // Intentionally do NOT call client.close(): leaving scope runs
  24468. // shutdown_and_close() with the WebSocket still open, which must send the
  24469. // close frame while the TLS session is still alive.
  24470. }
  24471. }
  24472. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24473. // shutdown_and_close() at the start of connect(), reproducing the same
  24474. // use-after-free within the test body rather than at scope exit. The second
  24475. // connect must succeed and echo, proving the close handshake ran over a live
  24476. // session. See the note above about memory-tool requirements.
  24477. TEST_F(WebSocketSSLIntegrationTest,
  24478. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24479. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24480. "/ws-echo");
  24481. client.enable_server_certificate_verification(false);
  24482. client.set_read_timeout(2, 0);
  24483. client.set_write_timeout(2, 0);
  24484. ASSERT_TRUE(client.connect());
  24485. ASSERT_TRUE(client.is_open());
  24486. ASSERT_TRUE(client.send("still open"));
  24487. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24488. // the still-open connection, which must not touch a freed TLS session.
  24489. ASSERT_TRUE(client.connect());
  24490. ASSERT_TRUE(client.is_open());
  24491. ASSERT_TRUE(client.send("after reconnect"));
  24492. std::string msg;
  24493. EXPECT_EQ(ws::Text, client.read(msg));
  24494. EXPECT_EQ("after reconnect", msg);
  24495. client.close();
  24496. }
  24497. #endif
  24498. #ifdef CPPHTTPLIB_SSL_ENABLED
  24499. class WebSocketSSLCATest : public ::testing::Test {
  24500. protected:
  24501. void SetUp() override {
  24502. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24503. SERVER_PRIVATE_KEY_FILE);
  24504. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24505. std::string msg;
  24506. while (ws.read(msg)) {
  24507. ws.send(msg);
  24508. }
  24509. });
  24510. port_ = server_->bind_to_any_port("127.0.0.1");
  24511. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24512. server_->wait_until_ready();
  24513. }
  24514. void TearDown() override {
  24515. server_->stop();
  24516. if (server_thread_.joinable()) { server_thread_.join(); }
  24517. }
  24518. std::string url() const {
  24519. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24520. }
  24521. std::unique_ptr<SSLServer> server_;
  24522. std::thread server_thread_;
  24523. int port_ = 0;
  24524. };
  24525. // A custom CA loaded as PEM verifies the server with full certificate
  24526. // verification enabled
  24527. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24528. ws::WebSocketClient client(url());
  24529. std::string cert;
  24530. read_file(SERVER_CERT2_FILE, cert);
  24531. client.load_ca_cert_store(cert.c_str(), cert.size());
  24532. ASSERT_TRUE(client.connect());
  24533. ASSERT_TRUE(client.send("hello"));
  24534. std::string msg;
  24535. EXPECT_EQ(ws::Text, client.read(msg));
  24536. EXPECT_EQ("hello", msg);
  24537. client.close();
  24538. }
  24539. // A custom CA that does not cover the server must fail verification (the
  24540. // custom CA is exclusive; system certs are not loaded alongside it)
  24541. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24542. ws::WebSocketClient client(url());
  24543. std::string cert;
  24544. read_file(CLIENT_CA_CERT_FILE, cert);
  24545. client.load_ca_cert_store(cert.c_str(), cert.size());
  24546. auto res = client.connect();
  24547. ASSERT_FALSE(res);
  24548. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24549. EXPECT_EQ(-1, res.status());
  24550. EXPECT_NE(0u, res.ssl_backend_error());
  24551. }
  24552. // The same CA as a file path rather than PEM in memory
  24553. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24554. ws::WebSocketClient client(url());
  24555. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24556. ASSERT_TRUE(client.connect());
  24557. ASSERT_TRUE(client.send("hello"));
  24558. std::string msg;
  24559. EXPECT_EQ(ws::Text, client.read(msg));
  24560. EXPECT_EQ("hello", msg);
  24561. client.close();
  24562. }
  24563. // ...and a CA file that does not cover the server still fails, so it is the
  24564. // path above that decides the outcome
  24565. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24566. ws::WebSocketClient client(url());
  24567. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24568. ASSERT_FALSE(client.connect());
  24569. }
  24570. // Regression test: reconnecting with a native custom CA store used to reuse
  24571. // a store handle the previous TLS context had already freed (use-after-free
  24572. // under the OpenSSL backend). The context now lives as long as the client.
  24573. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24574. ws::WebSocketClient client(url());
  24575. std::string cert;
  24576. read_file(SERVER_CERT2_FILE, cert);
  24577. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24578. ASSERT_TRUE(client.connect());
  24579. client.close();
  24580. ASSERT_TRUE(client.connect());
  24581. ASSERT_TRUE(client.send("again"));
  24582. std::string msg;
  24583. EXPECT_EQ(ws::Text, client.read(msg));
  24584. EXPECT_EQ("again", msg);
  24585. client.close();
  24586. }
  24587. // Regression test: a certificate with a trusted chain but no identity match
  24588. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24589. // verification entirely for IP hosts, so this connection succeeded there.
  24590. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24591. // chain verification while the identity check must still fail.
  24592. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24594. ASSERT_TRUE(svr.is_valid());
  24595. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24596. std::string msg;
  24597. while (ws.read(msg)) {
  24598. ws.send(msg);
  24599. }
  24600. });
  24601. auto port = svr.bind_to_any_port("127.0.0.1");
  24602. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24603. auto se = detail::scope_exit([&] {
  24604. svr.stop();
  24605. t.join();
  24606. });
  24607. svr.wait_until_ready();
  24608. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24609. "/echo");
  24610. std::string cert;
  24611. read_file(SERVER_CERT_FILE, cert);
  24612. client.load_ca_cert_store(cert.c_str(), cert.size());
  24613. ASSERT_FALSE(client.connect());
  24614. }
  24615. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24616. // SNI, so nothing binds the host name to the TLS session. These bind the
  24617. // server to "localhost" instead, the only shape that exercises the SNI and
  24618. // hostname-verification path with certificate verification left enabled.
  24619. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24620. protected:
  24621. void Start(const char *cert_file) {
  24622. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24623. SERVER_PRIVATE_KEY_FILE);
  24624. ASSERT_TRUE(server_->is_valid());
  24625. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24626. std::string msg;
  24627. while (ws.read(msg)) {
  24628. ws.send(msg);
  24629. }
  24630. });
  24631. port_ = server_->bind_to_any_port("localhost");
  24632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24633. server_->wait_until_ready();
  24634. }
  24635. void TearDown() override {
  24636. if (server_) { server_->stop(); }
  24637. if (server_thread_.joinable()) { server_thread_.join(); }
  24638. }
  24639. std::string url() const {
  24640. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24641. }
  24642. std::unique_ptr<SSLServer> server_;
  24643. std::thread server_thread_;
  24644. int port_ = 0;
  24645. };
  24646. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24647. // out and the connection is usable
  24648. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24649. Start(SERVER_CERT2_FILE);
  24650. ws::WebSocketClient client(url());
  24651. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24652. ASSERT_TRUE(client.connect());
  24653. ASSERT_TRUE(client.send("hello"));
  24654. std::string msg;
  24655. EXPECT_EQ(ws::Text, client.read(msg));
  24656. EXPECT_EQ("hello", msg);
  24657. client.close();
  24658. }
  24659. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24660. // while the identity check must still reject "localhost"
  24661. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24662. Start(SERVER_CERT_FILE);
  24663. ws::WebSocketClient client(url());
  24664. client.set_ca_cert_path(SERVER_CERT_FILE);
  24665. auto res = client.connect();
  24666. ASSERT_FALSE(res);
  24667. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24668. EXPECT_EQ(-1, res.status());
  24669. }
  24670. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24671. // disabled: the chain is still checked, only the identity check is skipped
  24672. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24673. Start(SERVER_CERT_FILE);
  24674. ws::WebSocketClient client(url());
  24675. client.set_ca_cert_path(SERVER_CERT_FILE);
  24676. client.enable_server_hostname_verification(false);
  24677. ASSERT_TRUE(client.connect());
  24678. ASSERT_TRUE(client.send("hello"));
  24679. std::string msg;
  24680. EXPECT_EQ(ws::Text, client.read(msg));
  24681. EXPECT_EQ("hello", msg);
  24682. client.close();
  24683. }
  24684. // A CA that did not sign the server certificate fails the chain, even though
  24685. // the name would match
  24686. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24687. Start(SERVER_CERT2_FILE);
  24688. ws::WebSocketClient client(url());
  24689. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24690. ASSERT_FALSE(client.connect());
  24691. }
  24692. // With verification disabled, neither the chain nor the name is checked
  24693. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24694. Start(SERVER_CERT_FILE);
  24695. ws::WebSocketClient client(url());
  24696. client.enable_server_certificate_verification(false);
  24697. ASSERT_TRUE(client.connect());
  24698. ASSERT_TRUE(client.send("hello"));
  24699. std::string msg;
  24700. EXPECT_EQ(ws::Text, client.read(msg));
  24701. EXPECT_EQ("hello", msg);
  24702. client.close();
  24703. }
  24704. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24705. protected:
  24706. void SetUp() override {
  24707. server_ = httplib::detail::make_unique<SSLServer>(
  24708. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24709. ASSERT_TRUE(server_->is_valid());
  24710. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24711. std::string msg;
  24712. while (ws.read(msg)) {
  24713. ws.send(msg);
  24714. }
  24715. });
  24716. port_ = server_->bind_to_any_port("localhost");
  24717. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24718. server_->wait_until_ready();
  24719. }
  24720. void TearDown() override {
  24721. server_->stop();
  24722. if (server_thread_.joinable()) { server_thread_.join(); }
  24723. }
  24724. std::string url() const {
  24725. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24726. }
  24727. void ConnectWithClientCert(const std::string &client_cert_file,
  24728. const std::string &client_private_key_file,
  24729. const char *private_key_password) {
  24730. std::string cert_pem, key_pem;
  24731. read_file(client_cert_file, cert_pem);
  24732. read_file(client_private_key_file, key_pem);
  24733. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24734. key_pem.c_str(), key_pem.size(),
  24735. private_key_password};
  24736. ConnectWithPem(pem);
  24737. }
  24738. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24739. ws::WebSocketClient client(url(), pem);
  24740. ASSERT_TRUE(client.is_valid());
  24741. client.enable_server_certificate_verification(false);
  24742. ASSERT_TRUE(client.connect());
  24743. ASSERT_TRUE(client.send("hello"));
  24744. std::string msg;
  24745. EXPECT_EQ(ws::Text, client.read(msg));
  24746. EXPECT_EQ("hello", msg);
  24747. client.close();
  24748. }
  24749. std::unique_ptr<SSLServer> server_;
  24750. std::thread server_thread_;
  24751. int port_ = 0;
  24752. };
  24753. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24754. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24755. }
  24756. // Control for the tests above: the fixture's server really does require a
  24757. // client certificate, so it is the PEM the constructor installed that decides
  24758. // the outcome.
  24759. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24760. ws::WebSocketClient client(url());
  24761. ASSERT_TRUE(client.is_valid());
  24762. client.enable_server_certificate_verification(false);
  24763. EXPECT_FALSE(client.connect());
  24764. }
  24765. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24766. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24767. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24768. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24769. }
  24770. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24771. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24772. std::string cert_pem, key_pem;
  24773. read_file(CLIENT_CERT_FILE, cert_pem);
  24774. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24775. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24776. std::vector<char> key(key_pem.begin(), key_pem.end());
  24777. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24778. key.size(), nullptr};
  24779. ConnectWithPem(pem);
  24780. }
  24781. #endif
  24782. #if !defined(_WIN32)
  24783. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24784. auto secret_dir = std::string("./symlink_test_secret");
  24785. auto served_dir = std::string("./symlink_test_served");
  24786. auto secret_file = secret_dir + "/secret.txt";
  24787. auto symlink_path = served_dir + "/escape";
  24788. // Setup: create directories and files
  24789. mkdir(secret_dir.c_str(), 0755);
  24790. mkdir(served_dir.c_str(), 0755);
  24791. {
  24792. std::ofstream ofs(secret_file);
  24793. ofs << "SECRET_DATA";
  24794. }
  24795. // Create symlink using absolute path so it resolves correctly
  24796. #ifdef PATH_MAX
  24797. char abs_secret[PATH_MAX];
  24798. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24799. #else
  24800. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24801. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24802. ASSERT_NE(nullptr, abs_secret);
  24803. #endif
  24804. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24805. auto se = detail::scope_exit([&] {
  24806. unlink(symlink_path.c_str());
  24807. unlink(secret_file.c_str());
  24808. rmdir(served_dir.c_str());
  24809. rmdir(secret_dir.c_str());
  24810. });
  24811. Server svr;
  24812. svr.set_mount_point("/", served_dir);
  24813. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24814. auto se2 = detail::scope_exit([&] {
  24815. svr.stop();
  24816. listen_thread.join();
  24817. });
  24818. svr.wait_until_ready();
  24819. Client cli("localhost", PORT);
  24820. // Symlink pointing outside base dir should be blocked
  24821. auto res = cli.Get("/escape/secret.txt");
  24822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24823. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24824. }
  24825. #endif
  24826. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24827. // "GET /smuggled" request), reads the first response, and only then sends the
  24828. // embedded request as the body. Returns how many times /smuggled ran.
  24829. //
  24830. // The body is sent AFTER receiving the first response (as in the original
  24831. // PoC) so that the stream_line_reader cannot buffer it together with the
  24832. // headers of the first request.
  24833. static int count_smuggled_requests(const std::string &outer_head,
  24834. std::string &first_response) {
  24835. Server svr;
  24836. svr.set_mount_point("/", "./www");
  24837. std::atomic<int> smuggled_count(0);
  24838. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24839. smuggled_count++;
  24840. res.set_content("oops", "text/plain");
  24841. });
  24842. svr.Post("/post", [&](const Request &req, Response &res) {
  24843. res.set_content(req.body, "text/plain");
  24844. });
  24845. auto port = svr.bind_to_any_port("localhost");
  24846. thread t = thread([&] { svr.listen_after_bind(); });
  24847. auto se = detail::scope_exit([&] {
  24848. svr.stop();
  24849. t.join();
  24850. });
  24851. svr.wait_until_ready();
  24852. auto error = Error::Success;
  24853. auto sock = detail::create_client_socket(
  24854. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24855. /*connection_timeout_sec=*/2, 0,
  24856. /*read_timeout_sec=*/2, 0,
  24857. /*write_timeout_sec=*/2, 0, std::string(), error);
  24858. EXPECT_NE(INVALID_SOCKET, sock);
  24859. if (sock == INVALID_SOCKET) { return -1; }
  24860. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24861. // The "smuggled" request will be sent as the body of the outer request
  24862. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24863. "Host: localhost\r\n"
  24864. "Connection: close\r\n"
  24865. "\r\n";
  24866. auto head = outer_head;
  24867. auto len = std::to_string(smuggled.size());
  24868. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24869. pos = head.find("{len}", pos + len.size())) {
  24870. head.replace(pos, 5, len);
  24871. }
  24872. // Step 1: Send only the outer request headers (no body yet)
  24873. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24874. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24875. // Step 2: Read the first response
  24876. char buf[4096];
  24877. for (;;) {
  24878. auto n = recv(sock, buf, sizeof(buf), 0);
  24879. if (n <= 0) break;
  24880. first_response.append(buf, static_cast<size_t>(n));
  24881. // Stop once we have a complete response (headers + body)
  24882. auto hdr_end = first_response.find("\r\n\r\n");
  24883. if (hdr_end != std::string::npos) {
  24884. // Check for Content-Length to know when the body is complete
  24885. auto cl_pos = first_response.find("Content-Length:");
  24886. if (cl_pos != std::string::npos) {
  24887. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24888. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24889. auto cl = std::stoul(
  24890. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24891. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24892. } else {
  24893. break; // No Content-Length, assume headers-only response
  24894. }
  24895. }
  24896. }
  24897. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24898. // vulnerable server the keep-alive loop reads this as a second request. The
  24899. // server may already have closed the connection, so the result is ignored.
  24900. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24901. // Half-close so that a server which drained the body sees EOF and closes,
  24902. // instead of the read below waiting for the read timeout.
  24903. #ifdef _WIN32
  24904. ::shutdown(sock, SD_SEND);
  24905. #else
  24906. ::shutdown(sock, SHUT_WR);
  24907. #endif
  24908. // Step 4: Read until the server closes the connection
  24909. for (;;) {
  24910. auto n = recv(sock, buf, sizeof(buf), 0);
  24911. if (n <= 0) break;
  24912. }
  24913. return smuggled_count.load();
  24914. }
  24915. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24916. // A GET request with Content-Length to a static file handler must have its
  24917. // body drained before the keep-alive connection is reused. Otherwise the
  24918. // unread body bytes are interpreted as the next HTTP request.
  24919. std::string first_response;
  24920. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24921. "Host: localhost\r\n"
  24922. "Content-Length: {len}\r\n"
  24923. "\r\n",
  24924. first_response));
  24925. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24926. }
  24927. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24928. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24929. // be answered with 400 and the connection closed. Treating it as "no body"
  24930. // leaves the body to be parsed as the next request.
  24931. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24932. const char *targets[] = {
  24933. "GET /file", // handler that never reads the body
  24934. "GET /not-found", // no handler matches (404)
  24935. "POST /post", // handler that reads the body
  24936. };
  24937. for (auto target : targets) {
  24938. for (auto value : values) {
  24939. std::string first_response;
  24940. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24941. " HTTP/1.1\r\n"
  24942. "Host: localhost\r\n"
  24943. "Content-Length: " +
  24944. value + "\r\n\r\n",
  24945. first_response))
  24946. << target << " with Content-Length: " << value;
  24947. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24948. << target << " with Content-Length: " << value;
  24949. }
  24950. }
  24951. }
  24952. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24953. // A 400 for an unparseable request line leaves the rest of the message
  24954. // unread, so the connection must be closed rather than reused.
  24955. std::string first_response;
  24956. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24957. "Host: localhost\r\n"
  24958. "Content-Length: {len}\r\n"
  24959. "\r\n",
  24960. first_response));
  24961. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24962. }
  24963. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24964. // Same as above for a header block that fails to parse.
  24965. std::string first_response;
  24966. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24967. "Host: localhost\r\n"
  24968. "Bad Header\r\n"
  24969. "Content-Length: {len}\r\n"
  24970. "\r\n",
  24971. first_response));
  24972. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24973. }
  24974. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24975. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24976. // server must not read another request on that connection, even when the
  24977. // request had no body to drain.
  24978. std::string first_response;
  24979. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24980. "Host: localhost\r\n"
  24981. "\r\n",
  24982. first_response));
  24983. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24984. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24985. }
  24986. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24987. // A content reader that stops early leaves the stream inside the body.
  24988. // Draining the whole Content-Length from there, or reading the body again,
  24989. // reads into the next request, and whatever follows is parsed as a request
  24990. // of its own.
  24991. Server svr;
  24992. std::atomic<int> smuggled_count(0);
  24993. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24994. svr.Post("/upload", [](const Request &req, Response &res,
  24995. const ContentReader &content_reader) {
  24996. // Stop at the last chunk, so the whole body has been read however it
  24997. // arrives.
  24998. auto length = req.get_header_value_u64("Content-Length");
  24999. size_t total = 0;
  25000. auto consumed = content_reader([&](const char *, size_t n) {
  25001. total += n;
  25002. return total < length;
  25003. });
  25004. EXPECT_FALSE(consumed);
  25005. if (req.has_param("retry")) {
  25006. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25007. }
  25008. // Replace the 400 the aborted read set, which would close the connection.
  25009. res.set_redirect("/done");
  25010. });
  25011. auto port = svr.bind_to_any_port(HOST);
  25012. thread t = thread([&] { svr.listen_after_bind(); });
  25013. auto se = detail::scope_exit([&] {
  25014. svr.stop();
  25015. t.join();
  25016. });
  25017. svr.wait_until_ready();
  25018. // A front end sees the second request as a POST whose body is the GET. The
  25019. // first body is as long as the POST's headers, so draining it again reads
  25020. // exactly those and leaves the GET to be parsed next.
  25021. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25022. "Host: localhost\r\n"
  25023. "\r\n";
  25024. std::string second_head = "POST /post HTTP/1.1\r\n"
  25025. "Host: localhost\r\n"
  25026. "Content-Length: " +
  25027. std::to_string(inner.size()) +
  25028. "\r\n"
  25029. "\r\n";
  25030. for (auto target : {"/upload", "/upload?retry"}) {
  25031. smuggled_count = 0;
  25032. std::string request = "POST " + std::string(target) +
  25033. " HTTP/1.1\r\n"
  25034. "Host: localhost\r\n"
  25035. "Content-Length: " +
  25036. std::to_string(second_head.size()) +
  25037. "\r\n"
  25038. "\r\n" +
  25039. std::string(second_head.size(), 'A') + second_head +
  25040. inner;
  25041. std::string response;
  25042. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25043. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25044. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25045. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25046. EXPECT_EQ(0, smuggled_count.load()) << target;
  25047. }
  25048. }
  25049. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25050. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25051. // must be rejected with 400 Bad Request.
  25052. Server svr;
  25053. svr.Post("/test", [&](const Request &, Response &res) {
  25054. res.set_content("ok", "text/plain");
  25055. });
  25056. thread t = thread([&] { svr.listen(HOST, PORT); });
  25057. auto se = detail::scope_exit([&] {
  25058. svr.stop();
  25059. t.join();
  25060. ASSERT_FALSE(svr.is_running());
  25061. });
  25062. svr.wait_until_ready();
  25063. // Exact "chunked"
  25064. {
  25065. auto req = "POST /test HTTP/1.1\r\n"
  25066. "Host: localhost\r\n"
  25067. "Content-Length: 5\r\n"
  25068. "Transfer-Encoding: chunked\r\n"
  25069. "Connection: close\r\n"
  25070. "\r\n"
  25071. "hello";
  25072. std::string response;
  25073. ASSERT_TRUE(send_request(1, req, &response));
  25074. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25075. response.substr(0, response.find("\r\n")));
  25076. }
  25077. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25078. {
  25079. auto req = "POST /test HTTP/1.1\r\n"
  25080. "Host: localhost\r\n"
  25081. "Content-Length: 5\r\n"
  25082. "Transfer-Encoding: gzip, chunked\r\n"
  25083. "Connection: close\r\n"
  25084. "\r\n"
  25085. "hello";
  25086. std::string response;
  25087. ASSERT_TRUE(send_request(1, req, &response));
  25088. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25089. response.substr(0, response.find("\r\n")));
  25090. }
  25091. }
  25092. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25093. Server svr;
  25094. svr.Post("/test", [&](const Request &, Response &res) {
  25095. res.set_content("ok", "text/plain");
  25096. });
  25097. thread t = thread([&] { svr.listen(HOST, PORT); });
  25098. auto se = detail::scope_exit([&] {
  25099. svr.stop();
  25100. t.join();
  25101. ASSERT_FALSE(svr.is_running());
  25102. });
  25103. svr.wait_until_ready();
  25104. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25105. // length cannot be determined, so the server must answer 400 and close
  25106. // rather than treat the request as bodyless and leave the body in the
  25107. // socket for the next request to pick up.
  25108. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25109. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25110. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25111. std::string response;
  25112. ASSERT_TRUE(send_request(1, req, &response));
  25113. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25114. response.substr(0, response.find("\r\n")))
  25115. << transfer_encoding;
  25116. }
  25117. // RFC 9110 5.3: the codings may also be split across several
  25118. // Transfer-Encoding lines, which combine in the order they were received.
  25119. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25120. // just like the single-line "chunked, gzip" above.
  25121. {
  25122. auto req = "POST /test HTTP/1.1\r\n"
  25123. "Host: localhost\r\n"
  25124. "Transfer-Encoding: chunked\r\n"
  25125. "Transfer-Encoding: gzip\r\n"
  25126. "\r\n"
  25127. "0\r\n\r\n";
  25128. std::string response;
  25129. ASSERT_TRUE(send_request(1, req, &response));
  25130. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25131. response.substr(0, response.find("\r\n")));
  25132. }
  25133. // A sequence ending in chunked stays valid.
  25134. auto req = "POST /test HTTP/1.1\r\n"
  25135. "Host: localhost\r\n"
  25136. "Transfer-Encoding: gzip, chunked\r\n"
  25137. "Connection: close\r\n"
  25138. "\r\n"
  25139. "0\r\n\r\n";
  25140. std::string response;
  25141. ASSERT_TRUE(send_request(1, req, &response));
  25142. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25143. // ...including when it is spread over several lines.
  25144. auto split_req = "POST /test HTTP/1.1\r\n"
  25145. "Host: localhost\r\n"
  25146. "Transfer-Encoding: gzip\r\n"
  25147. "Transfer-Encoding: chunked\r\n"
  25148. "Connection: close\r\n"
  25149. "\r\n"
  25150. "0\r\n\r\n";
  25151. std::string split_response;
  25152. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25153. EXPECT_EQ("HTTP/1.1 200 OK",
  25154. split_response.substr(0, split_response.find("\r\n")));
  25155. }
  25156. // Regression for issue #2450: a DELETE without Content-Length on a
  25157. // keep-alive connection must not let the post-response drain consume the
  25158. // next request's bytes.
  25159. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25160. Server svr;
  25161. std::atomic<int> delete_count(0);
  25162. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25163. delete_count++;
  25164. res.status = StatusCode::NoContent_204;
  25165. });
  25166. auto port = svr.bind_to_any_port(HOST);
  25167. thread t = thread([&] { svr.listen_after_bind(); });
  25168. auto se = detail::scope_exit([&] {
  25169. svr.stop();
  25170. t.join();
  25171. });
  25172. svr.wait_until_ready();
  25173. auto error = Error::Success;
  25174. auto sock = detail::create_client_socket(
  25175. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25176. /*connection_timeout_sec=*/2, 0,
  25177. /*read_timeout_sec=*/2, 0,
  25178. /*write_timeout_sec=*/2, 0, std::string(), error);
  25179. ASSERT_NE(INVALID_SOCKET, sock);
  25180. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25181. auto send_request_and_read_response = [&](const std::string &req,
  25182. std::string &out) -> bool {
  25183. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25184. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25185. char buf[4096];
  25186. for (;;) {
  25187. auto n = recv(sock, buf, sizeof(buf), 0);
  25188. if (n <= 0) { return !out.empty(); }
  25189. out.append(buf, static_cast<size_t>(n));
  25190. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25191. }
  25192. };
  25193. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25194. "Host: localhost\r\n"
  25195. "\r\n";
  25196. std::string resp1;
  25197. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25198. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25199. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25200. "Host: localhost\r\n"
  25201. "Connection: close\r\n"
  25202. "\r\n";
  25203. std::string resp2;
  25204. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25205. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25206. EXPECT_EQ(2, delete_count.load());
  25207. }
  25208. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25209. Server svr;
  25210. svr.Post("/ingest", [&](const Request &, Response &res,
  25211. const ContentReader &content_reader) {
  25212. auto consumed = content_reader([](const char *, size_t) { return false; });
  25213. EXPECT_FALSE(consumed);
  25214. res.status = StatusCode::Conflict_409;
  25215. res.set_header("Connection", "close");
  25216. });
  25217. auto port = svr.bind_to_any_port(HOST);
  25218. thread t = thread([&] { svr.listen_after_bind(); });
  25219. auto se = detail::scope_exit([&] {
  25220. svr.stop();
  25221. t.join();
  25222. });
  25223. svr.wait_until_ready();
  25224. auto error = Error::Success;
  25225. auto sock = detail::create_client_socket(
  25226. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25227. /*connection_timeout_sec=*/2, 0,
  25228. /*read_timeout_sec=*/1, 0,
  25229. /*write_timeout_sec=*/2, 0, std::string(), error);
  25230. ASSERT_NE(INVALID_SOCKET, sock);
  25231. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25232. std::string request = "POST /ingest HTTP/1.1\r\n"
  25233. "Host: localhost\r\n"
  25234. "Transfer-Encoding: chunked\r\n"
  25235. "\r\n"
  25236. "4\r\n"
  25237. "data\r\n";
  25238. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25239. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25240. std::string response;
  25241. ssize_t received = 0;
  25242. do {
  25243. char buf[4096];
  25244. received = recv(sock, buf, sizeof(buf), 0);
  25245. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25246. } while (received > 0);
  25247. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25248. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25249. EXPECT_EQ(0, received);
  25250. }
  25251. namespace no_proxy_test {
  25252. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25253. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25254. // calling listen().
  25255. class ScopedServer {
  25256. public:
  25257. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25258. ~ScopedServer() {
  25259. svr_.stop();
  25260. if (th_.joinable()) { th_.join(); }
  25261. }
  25262. Server &svr() { return svr_; }
  25263. int port() const { return port_; }
  25264. void listen() {
  25265. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25266. svr_.wait_until_ready();
  25267. }
  25268. private:
  25269. Server svr_;
  25270. std::thread th_;
  25271. int port_ = 0;
  25272. };
  25273. class ProxyAndTargetServers {
  25274. public:
  25275. ProxyAndTargetServers() {
  25276. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25277. proxy_hits_++;
  25278. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25279. res.set_content("via-proxy", "text/plain");
  25280. });
  25281. target_.Get(".*", [this](const Request &req, Response &res) {
  25282. target_hits_++;
  25283. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25284. res.set_content("direct", "text/plain");
  25285. });
  25286. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25287. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25288. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25289. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25290. proxy_mock_.wait_until_ready();
  25291. target_.wait_until_ready();
  25292. }
  25293. ~ProxyAndTargetServers() {
  25294. proxy_mock_.stop();
  25295. target_.stop();
  25296. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25297. if (target_thread_.joinable()) { target_thread_.join(); }
  25298. }
  25299. Server &proxy_mock() { return proxy_mock_; }
  25300. Server &target() { return target_; }
  25301. int proxy_port() const { return proxy_port_; }
  25302. int target_port() const { return target_port_; }
  25303. int proxy_hits() const { return proxy_hits_.load(); }
  25304. int target_hits() const { return target_hits_.load(); }
  25305. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25306. void reset_counters() {
  25307. proxy_hits_ = 0;
  25308. target_hits_ = 0;
  25309. last_had_proxy_authz_ = false;
  25310. }
  25311. private:
  25312. Server proxy_mock_;
  25313. Server target_;
  25314. std::thread proxy_thread_;
  25315. std::thread target_thread_;
  25316. int proxy_port_ = 0;
  25317. int target_port_ = 0;
  25318. std::atomic<int> proxy_hits_{0};
  25319. std::atomic<int> target_hits_{0};
  25320. std::atomic<bool> last_had_proxy_authz_{false};
  25321. };
  25322. inline std::unique_ptr<Client> make_client(const std::string &host,
  25323. ProxyAndTargetServers &s) {
  25324. auto cli = detail::make_unique<Client>(host, s.target_port());
  25325. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25326. cli->set_proxy("127.0.0.1", s.proxy_port());
  25327. return cli;
  25328. }
  25329. } // namespace no_proxy_test
  25330. using no_proxy_test::make_client;
  25331. using no_proxy_test::ProxyAndTargetServers;
  25332. // A stream request carries the credentials a buffered request does
  25333. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25334. no_proxy_test::ScopedServer origin;
  25335. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25336. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25337. });
  25338. origin.listen();
  25339. Client cli("127.0.0.1", origin.port());
  25340. cli.set_basic_auth("user", "pass");
  25341. auto handle = cli.open_stream("GET", "/x");
  25342. ASSERT_TRUE(handle.is_valid());
  25343. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25344. Client bearer("127.0.0.1", origin.port());
  25345. bearer.set_bearer_token_auth("tok");
  25346. auto handle2 = bearer.open_stream("GET", "/x");
  25347. ASSERT_TRUE(handle2.is_valid());
  25348. EXPECT_EQ("Bearer tok", read_all(handle2));
  25349. }
  25350. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25351. // takes its own credentials, as for a buffered request
  25352. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25353. std::string target, authz, proxy_authz;
  25354. no_proxy_test::ScopedServer proxy;
  25355. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25356. target = req.target;
  25357. authz = req.get_header_value("Authorization");
  25358. proxy_authz = req.get_header_value("Proxy-Authorization");
  25359. res.set_content("ok", "text/plain");
  25360. });
  25361. proxy.listen();
  25362. Client cli("origin.example", 8080);
  25363. cli.set_proxy("127.0.0.1", proxy.port());
  25364. cli.set_proxy_basic_auth("puser", "ppass");
  25365. cli.set_basic_auth("user", "pass");
  25366. auto handle = cli.open_stream("GET", "/x");
  25367. ASSERT_TRUE(handle.is_valid());
  25368. EXPECT_EQ("ok", read_all(handle));
  25369. EXPECT_EQ("http://origin.example:8080/x", target);
  25370. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25371. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25372. }
  25373. TEST(NoProxyTest, ExactHostnameBypasses) {
  25374. ProxyAndTargetServers s;
  25375. auto cli = make_client("example.com", s);
  25376. cli->set_no_proxy({"example.com"});
  25377. auto res = cli->Get("/");
  25378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25379. EXPECT_EQ(0, s.proxy_hits());
  25380. EXPECT_EQ(1, s.target_hits());
  25381. }
  25382. TEST(NoProxyTest, SubdomainBypasses) {
  25383. ProxyAndTargetServers s;
  25384. auto cli = make_client("foo.example.com", s);
  25385. cli->set_no_proxy({"example.com"});
  25386. auto res = cli->Get("/");
  25387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25388. EXPECT_EQ(0, s.proxy_hits());
  25389. EXPECT_EQ(1, s.target_hits());
  25390. }
  25391. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25392. // Regression guard: "evilexample.com" must not be considered a subdomain
  25393. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25394. // check would let traffic bypass the proxy and leak credentials direct
  25395. // to the attacker host.
  25396. ProxyAndTargetServers s;
  25397. auto cli = make_client("evilexample.com", s);
  25398. cli->set_no_proxy({"example.com"});
  25399. auto res = cli->Get("/");
  25400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25401. EXPECT_GE(s.proxy_hits(), 1);
  25402. EXPECT_EQ(0, s.target_hits());
  25403. }
  25404. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25405. ProxyAndTargetServers s;
  25406. auto cli = make_client("example.com.evil.com", s);
  25407. cli->set_no_proxy({"example.com"});
  25408. auto res = cli->Get("/");
  25409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25410. EXPECT_GE(s.proxy_hits(), 1);
  25411. EXPECT_EQ(0, s.target_hits());
  25412. }
  25413. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25414. ProxyAndTargetServers s;
  25415. auto cli = make_client("example.com", s);
  25416. cli->set_no_proxy({".example.com"});
  25417. auto res = cli->Get("/");
  25418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25419. EXPECT_EQ(0, s.proxy_hits());
  25420. EXPECT_EQ(1, s.target_hits());
  25421. }
  25422. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25423. ProxyAndTargetServers s;
  25424. auto cli = make_client("Example.COM", s);
  25425. cli->set_no_proxy({"EXAMPLE.com"});
  25426. auto res = cli->Get("/");
  25427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25428. EXPECT_EQ(0, s.proxy_hits());
  25429. EXPECT_EQ(1, s.target_hits());
  25430. }
  25431. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25432. ProxyAndTargetServers s;
  25433. auto cli = make_client("example.com.", s);
  25434. cli->set_no_proxy({"example.com"});
  25435. auto res = cli->Get("/");
  25436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25437. EXPECT_EQ(0, s.proxy_hits());
  25438. EXPECT_EQ(1, s.target_hits());
  25439. }
  25440. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25441. // Trailing dots must be normalized on BOTH sides — host and entry.
  25442. // An implementation that only strips the host-side trailing dot would
  25443. // fail to match host "example.com" against entry "example.com." because
  25444. // a literal substring search would compare 11 chars against 12.
  25445. ProxyAndTargetServers s;
  25446. auto cli = make_client("example.com", s);
  25447. cli->set_no_proxy({"example.com."});
  25448. auto res = cli->Get("/");
  25449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25450. EXPECT_EQ(0, s.proxy_hits());
  25451. EXPECT_EQ(1, s.target_hits());
  25452. }
  25453. TEST(NoProxyTest, WildcardBypassesEverything) {
  25454. ProxyAndTargetServers s;
  25455. auto cli = make_client("anything.invalid.test", s);
  25456. cli->set_no_proxy({"*"});
  25457. auto res = cli->Get("/");
  25458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25459. EXPECT_EQ(0, s.proxy_hits());
  25460. EXPECT_EQ(1, s.target_hits());
  25461. }
  25462. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25463. ProxyAndTargetServers s;
  25464. Client cli("127.0.0.1", s.target_port());
  25465. cli.set_proxy("127.0.0.1", s.proxy_port());
  25466. cli.set_no_proxy({"127.0.0.1"});
  25467. auto res = cli.Get("/");
  25468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25469. EXPECT_EQ(0, s.proxy_hits());
  25470. EXPECT_EQ(1, s.target_hits());
  25471. }
  25472. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25473. ProxyAndTargetServers s;
  25474. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25475. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25476. cli.set_proxy("127.0.0.1", s.proxy_port());
  25477. cli.set_no_proxy({"::1"});
  25478. auto res = cli.Get("/");
  25479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25480. EXPECT_EQ(0, s.proxy_hits());
  25481. EXPECT_EQ(1, s.target_hits());
  25482. }
  25483. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25484. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25485. // must still be recognized as IPv6 for CIDR matching. Implementations
  25486. // that detect IPv6 only when the host begins with '[' would parse the
  25487. // host as a hostname and miss the match.
  25488. ProxyAndTargetServers s;
  25489. Client cli("fe80::1", s.target_port());
  25490. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25491. cli.set_proxy("127.0.0.1", s.proxy_port());
  25492. cli.set_no_proxy({"fe80::/10"});
  25493. auto res = cli.Get("/");
  25494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25495. EXPECT_EQ(0, s.proxy_hits());
  25496. EXPECT_EQ(1, s.target_hits());
  25497. }
  25498. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25499. ProxyAndTargetServers s;
  25500. Client cli("::1", s.target_port());
  25501. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25502. cli.set_proxy("127.0.0.1", s.proxy_port());
  25503. cli.set_no_proxy({"[::1]"});
  25504. auto res = cli.Get("/");
  25505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25506. EXPECT_EQ(0, s.proxy_hits());
  25507. EXPECT_EQ(1, s.target_hits());
  25508. }
  25509. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25510. ProxyAndTargetServers s;
  25511. Client cli("fe80::1", s.target_port());
  25512. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25513. cli.set_proxy("127.0.0.1", s.proxy_port());
  25514. cli.set_no_proxy({"[fe80::]/10"});
  25515. auto res = cli.Get("/");
  25516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25517. EXPECT_EQ(0, s.proxy_hits());
  25518. EXPECT_EQ(1, s.target_hits());
  25519. }
  25520. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25521. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25522. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25523. // tricks via address-family conversion.
  25524. ProxyAndTargetServers s;
  25525. Client cli("::ffff:127.0.0.1", s.target_port());
  25526. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25527. cli.set_proxy("127.0.0.1", s.proxy_port());
  25528. cli.set_no_proxy({"127.0.0.1"});
  25529. auto res = cli.Get("/");
  25530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25531. EXPECT_GE(s.proxy_hits(), 1);
  25532. EXPECT_EQ(0, s.target_hits());
  25533. }
  25534. TEST(NoProxyTest, IPv4CidrMatch) {
  25535. ProxyAndTargetServers s;
  25536. Client cli("127.0.0.1", s.target_port());
  25537. cli.set_proxy("127.0.0.1", s.proxy_port());
  25538. cli.set_no_proxy({"127.0.0.0/8"});
  25539. auto res = cli.Get("/");
  25540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25541. EXPECT_EQ(0, s.proxy_hits());
  25542. EXPECT_EQ(1, s.target_hits());
  25543. }
  25544. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25545. ProxyAndTargetServers s;
  25546. Client cli("127.0.0.1", s.target_port());
  25547. cli.set_proxy("127.0.0.1", s.proxy_port());
  25548. cli.set_no_proxy({"10.0.0.0/8"});
  25549. auto res = cli.Get("/");
  25550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25551. EXPECT_GE(s.proxy_hits(), 1);
  25552. EXPECT_EQ(0, s.target_hits());
  25553. }
  25554. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25555. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25556. // IPv4 target matches.
  25557. ProxyAndTargetServers s;
  25558. Client cli("127.0.0.1", s.target_port());
  25559. cli.set_proxy("127.0.0.1", s.proxy_port());
  25560. cli.set_no_proxy({"0.0.0.0/0"});
  25561. auto res = cli.Get("/");
  25562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25563. EXPECT_EQ(0, s.proxy_hits());
  25564. EXPECT_EQ(1, s.target_hits());
  25565. }
  25566. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25567. ProxyAndTargetServers s;
  25568. Client cli("127.0.0.1", s.target_port());
  25569. cli.set_proxy("127.0.0.1", s.proxy_port());
  25570. cli.set_no_proxy({"127.0.0.1"});
  25571. auto res = cli.Get("/");
  25572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25573. EXPECT_EQ(0, s.proxy_hits());
  25574. EXPECT_EQ(1, s.target_hits());
  25575. }
  25576. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25577. ProxyAndTargetServers s;
  25578. Client cli("127.0.0.1", s.target_port());
  25579. cli.set_proxy("127.0.0.1", s.proxy_port());
  25580. cli.set_no_proxy({"127.0.0.0/33"});
  25581. auto res = cli.Get("/");
  25582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25583. EXPECT_GE(s.proxy_hits(), 1);
  25584. EXPECT_EQ(0, s.target_hits());
  25585. }
  25586. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25587. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25588. ProxyAndTargetServers s;
  25589. Client cli("127.0.0.1", s.target_port());
  25590. cli.set_proxy("127.0.0.1", s.proxy_port());
  25591. cli.set_no_proxy({"127.0.0.1/"});
  25592. auto res = cli.Get("/");
  25593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25594. EXPECT_GE(s.proxy_hits(), 1);
  25595. EXPECT_EQ(0, s.target_hits());
  25596. }
  25597. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25598. ProxyAndTargetServers s;
  25599. auto cli = make_client("internal.corp", s);
  25600. cli->set_proxy_basic_auth("u", "p");
  25601. cli->set_no_proxy({"internal.corp"});
  25602. auto res = cli->Get("/");
  25603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25604. EXPECT_EQ(1, s.target_hits());
  25605. EXPECT_EQ(0, s.proxy_hits());
  25606. EXPECT_FALSE(s.last_had_proxy_authz())
  25607. << "Proxy-Authorization must not be sent direct to the target";
  25608. }
  25609. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25610. ProxyAndTargetServers s;
  25611. auto cli = make_client("public.example", s);
  25612. cli->set_proxy_basic_auth("u", "p");
  25613. cli->set_no_proxy({"internal.corp"}); // does not match
  25614. auto res = cli->Get("/");
  25615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25616. EXPECT_GE(s.proxy_hits(), 1);
  25617. EXPECT_TRUE(s.last_had_proxy_authz());
  25618. }
  25619. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25620. std::atomic<int> hits{0};
  25621. std::atomic<int> hits_with_authz{0};
  25622. no_proxy_test::ScopedServer proxy_mock;
  25623. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25624. hits++;
  25625. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25626. if (req.target.find("/redir") != std::string::npos) {
  25627. res.set_redirect("http://other.example/landed");
  25628. } else {
  25629. res.set_content("via-proxy", "text/plain");
  25630. }
  25631. });
  25632. proxy_mock.listen();
  25633. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25634. hits = 0;
  25635. hits_with_authz = 0;
  25636. Client cli("public.example", 80);
  25637. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25638. cli.set_proxy_basic_auth(c.first, c.second);
  25639. cli.set_follow_location(true);
  25640. // The redirect to another host goes through the proxy as well
  25641. auto res = cli.Get("/redir");
  25642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25643. EXPECT_EQ(2, hits.load());
  25644. EXPECT_EQ(2, hits_with_authz.load());
  25645. }
  25646. }
  25647. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25648. ProxyAndTargetServers s;
  25649. auto cli = make_client("anything.test", s);
  25650. auto res = cli->Get("/");
  25651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25652. EXPECT_GE(s.proxy_hits(), 1);
  25653. EXPECT_EQ(0, s.target_hits());
  25654. }
  25655. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25656. ProxyAndTargetServers s;
  25657. auto cli = make_client("example.com", s);
  25658. cli->set_no_proxy({"example.com:8080"});
  25659. auto res = cli->Get("/");
  25660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25661. EXPECT_GE(s.proxy_hits(), 1);
  25662. EXPECT_EQ(0, s.target_hits());
  25663. }
  25664. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25665. ProxyAndTargetServers s;
  25666. auto cli = make_client("anything.test", s);
  25667. cli->set_no_proxy({"", " ", "\t"});
  25668. auto res = cli->Get("/");
  25669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25670. EXPECT_GE(s.proxy_hits(), 1);
  25671. EXPECT_EQ(0, s.target_hits());
  25672. }
  25673. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25674. // An entry with leading/trailing whitespace must still match — env-style
  25675. // values are commonly pasted with stray spaces and an implementation
  25676. // that feeds the raw token directly to inet_pton would fail to match
  25677. // valid CIDRs because of the spaces.
  25678. ProxyAndTargetServers s;
  25679. Client cli("127.0.0.1", s.target_port());
  25680. cli.set_proxy("127.0.0.1", s.proxy_port());
  25681. cli.set_no_proxy({" 127.0.0.0/8 "});
  25682. auto res = cli.Get("/");
  25683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25684. EXPECT_EQ(0, s.proxy_hits());
  25685. EXPECT_EQ(1, s.target_hits());
  25686. }
  25687. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25688. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25689. // go direct and must NOT carry Proxy-Authorization.
  25690. std::atomic<int> proxy_hits{0};
  25691. std::atomic<int> target_hits{0};
  25692. std::atomic<bool> target_saw_authz{false};
  25693. no_proxy_test::ScopedServer proxy_mock, target;
  25694. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25695. proxy_hits++;
  25696. res.status = 302;
  25697. res.set_header("Location", "http://127.0.0.1:" +
  25698. std::to_string(target.port()) + "/landed");
  25699. });
  25700. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25701. target_hits++;
  25702. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25703. res.set_content("direct", "text/plain");
  25704. });
  25705. proxy_mock.listen();
  25706. target.listen();
  25707. Client cli("public.example", target.port());
  25708. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25709. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25710. cli.set_proxy_basic_auth("u", "p");
  25711. cli.set_no_proxy({"127.0.0.1"});
  25712. cli.set_follow_location(true);
  25713. auto res = cli.Get("/redir");
  25714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25715. EXPECT_GE(proxy_hits.load(), 1);
  25716. EXPECT_GE(target_hits.load(), 1);
  25717. EXPECT_FALSE(target_saw_authz.load());
  25718. }
  25719. #ifdef CPPHTTPLIB_SSL_ENABLED
  25720. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25721. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25722. // proxy creds would be sent to the (possibly hostile) origin.
  25723. std::atomic<int> target_hits{0};
  25724. std::atomic<bool> target_saw_proxy_authz{false};
  25725. no_proxy_test::ScopedServer target;
  25726. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25727. target_hits++;
  25728. if (req.has_header("Proxy-Authorization")) {
  25729. target_saw_proxy_authz = true;
  25730. }
  25731. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25732. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25733. "nonce=\"abc\", algorithm=MD5");
  25734. });
  25735. target.listen();
  25736. // The proxy address is set to the target's port: the bypass MUST kick in;
  25737. // if it doesn't, the test still routes "via proxy" to the same server and
  25738. // the Proxy-Authorization assertion below catches the leak.
  25739. Client cli("evil.example", target.port());
  25740. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25741. cli.set_proxy("127.0.0.1", target.port());
  25742. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25743. cli.set_no_proxy({"evil.example"});
  25744. auto res = cli.Get("/x");
  25745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25746. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25747. EXPECT_EQ(1, target_hits.load());
  25748. EXPECT_FALSE(target_saw_proxy_authz.load());
  25749. }
  25750. #endif
  25751. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25752. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25753. std::atomic<int> proxy_hits{0};
  25754. std::atomic<int> bypass_hits{0};
  25755. std::atomic<bool> proxy_saw_c_url{false};
  25756. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25757. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25758. proxy_hits++;
  25759. if (req.path.find("/start") != std::string::npos) {
  25760. res.status = 302;
  25761. res.set_header("Location", "http://127.0.0.1:" +
  25762. std::to_string(bypass_server.port()) +
  25763. "/middle");
  25764. return;
  25765. }
  25766. if (req.path.find("/end") != std::string::npos) {
  25767. proxy_saw_c_url = true;
  25768. res.set_content("c-via-proxy", "text/plain");
  25769. return;
  25770. }
  25771. res.set_content("unexpected", "text/plain");
  25772. });
  25773. // public.example's "advertised" port is arbitrary (the request never lands
  25774. // there — it goes through the proxy), but use a dynamic value to stay
  25775. // friendly with sharded parallel runs.
  25776. int public_port = bypass_server.port();
  25777. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25778. bypass_hits++;
  25779. res.status = 302;
  25780. res.set_header("Location", "http://public.example:" +
  25781. std::to_string(public_port) + "/end");
  25782. });
  25783. proxy_mock.listen();
  25784. bypass_server.listen();
  25785. Client cli("public.example", public_port);
  25786. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25787. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25788. cli.set_no_proxy({"127.0.0.1"});
  25789. cli.set_follow_location(true);
  25790. auto res = cli.Get("/start");
  25791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25792. EXPECT_EQ(StatusCode::OK_200, res->status);
  25793. EXPECT_EQ("c-via-proxy", res->body);
  25794. EXPECT_GE(proxy_hits.load(), 2);
  25795. EXPECT_GE(bypass_hits.load(), 1);
  25796. EXPECT_TRUE(proxy_saw_c_url.load());
  25797. }
  25798. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25799. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25800. // request reconnects to the correct endpoint.
  25801. std::atomic<int> proxy_hits{0};
  25802. std::atomic<int> target_hits{0};
  25803. no_proxy_test::ScopedServer proxy_mock, target;
  25804. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25805. proxy_hits++;
  25806. res.set_content("via-proxy", "text/plain");
  25807. });
  25808. target.svr().Get(".*", [&](const Request &, Response &res) {
  25809. target_hits++;
  25810. res.set_content("direct", "text/plain");
  25811. });
  25812. proxy_mock.listen();
  25813. target.listen();
  25814. Client cli("public.example", target.port());
  25815. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25816. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25817. cli.set_keep_alive(true);
  25818. auto res1 = cli.Get("/a");
  25819. ASSERT_TRUE(res1);
  25820. EXPECT_EQ("via-proxy", res1->body);
  25821. EXPECT_EQ(1, proxy_hits.load());
  25822. EXPECT_EQ(0, target_hits.load());
  25823. cli.set_no_proxy({"public.example"});
  25824. auto res2 = cli.Get("/b");
  25825. ASSERT_TRUE(res2);
  25826. EXPECT_EQ("direct", res2->body);
  25827. EXPECT_EQ(1, proxy_hits.load());
  25828. EXPECT_EQ(1, target_hits.load());
  25829. }
  25830. // Forward declarations (see the base64_encode note).
  25831. namespace httplib {
  25832. namespace detail {
  25833. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25834. int shutdown_socket(socket_t sock) noexcept;
  25835. } // namespace detail
  25836. } // namespace httplib
  25837. namespace proxy_tunnel_test {
  25838. const char *const kTunnelEstablished =
  25839. "HTTP/1.1 200 Connection established\r\n\r\n";
  25840. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25841. using ConnectReply = std::function<std::string(const std::string &head)>;
  25842. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25843. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25844. class ScopedConnectProxy {
  25845. public:
  25846. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25847. : forward_port_(forward_port), reply_(std::move(reply)) {
  25848. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25849. if (listen_sock_ == INVALID_SOCKET) { return; }
  25850. auto a = loopback(0);
  25851. auto addr = reinterpret_cast<sockaddr *>(&a);
  25852. socklen_t alen = sizeof(a);
  25853. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25854. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25855. ::listen(listen_sock_, 4) != 0) {
  25856. return;
  25857. }
  25858. port_ = ntohs(a.sin_port);
  25859. th_ = std::thread([this] { run(); });
  25860. }
  25861. ~ScopedConnectProxy() {
  25862. if (th_.joinable()) {
  25863. stop_ = true;
  25864. auto wake = connect_to(port_);
  25865. th_.join();
  25866. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25867. }
  25868. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25869. }
  25870. int port() const { return port_; }
  25871. int connect_hits() const { return connect_hits_.load(); }
  25872. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25873. std::string connect_request() const {
  25874. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25875. return connect_request_;
  25876. }
  25877. private:
  25878. static sockaddr_in loopback(int port) {
  25879. sockaddr_in a{};
  25880. a.sin_family = AF_INET;
  25881. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25882. a.sin_port = htons(static_cast<unsigned short>(port));
  25883. return a;
  25884. }
  25885. static socket_t connect_to(int port) {
  25886. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25887. if (sock == INVALID_SOCKET) { return sock; }
  25888. auto a = loopback(port);
  25889. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25890. detail::close_socket(sock);
  25891. return INVALID_SOCKET;
  25892. }
  25893. return sock;
  25894. }
  25895. static bool send_all(socket_t sock, const char *data, size_t size) {
  25896. while (size > 0) {
  25897. auto n = detail::send_socket(sock, data, size, 0);
  25898. if (n <= 0) { return false; }
  25899. data += n;
  25900. size -= static_cast<size_t>(n);
  25901. }
  25902. return true;
  25903. }
  25904. void run() {
  25905. for (;;) {
  25906. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25907. if (stop_) {
  25908. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25909. return;
  25910. }
  25911. if (client == INVALID_SOCKET) { continue; }
  25912. serve(client);
  25913. detail::close_socket(client);
  25914. }
  25915. }
  25916. void serve(socket_t client) {
  25917. std::string head;
  25918. char buf[2048];
  25919. while (head.find("\r\n\r\n") == std::string::npos) {
  25920. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25921. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25922. if (n <= 0) { return; }
  25923. head.append(buf, static_cast<size_t>(n));
  25924. }
  25925. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25926. connect_hits_++;
  25927. {
  25928. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25929. connect_request_ = head;
  25930. }
  25931. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25932. if (!send_all(client, res.data(), res.size()) ||
  25933. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25934. return;
  25935. }
  25936. auto origin = connect_to(forward_port_);
  25937. if (origin == INVALID_SOCKET) { return; }
  25938. // When either side stops, shut both down so the other pump returns too.
  25939. auto pump = [&](socket_t from, socket_t to) {
  25940. char b[8192];
  25941. for (;;) {
  25942. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25943. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25944. }
  25945. detail::shutdown_socket(client);
  25946. detail::shutdown_socket(origin);
  25947. };
  25948. std::thread up([&] { pump(client, origin); });
  25949. pump(origin, client);
  25950. up.join();
  25951. detail::close_socket(origin);
  25952. }
  25953. int forward_port_;
  25954. ConnectReply reply_;
  25955. socket_t listen_sock_ = INVALID_SOCKET;
  25956. int port_ = 0;
  25957. std::thread th_;
  25958. std::atomic<bool> stop_{false};
  25959. std::atomic<int> connect_hits_{0};
  25960. mutable std::mutex connect_request_mutex_;
  25961. std::string connect_request_;
  25962. };
  25963. } // namespace proxy_tunnel_test
  25964. #ifdef CPPHTTPLIB_SSL_ENABLED
  25965. namespace proxy_tunnel_test {
  25966. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25967. class ScopedSSLServer {
  25968. public:
  25969. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25970. port_ = svr_.bind_to_any_port("127.0.0.1");
  25971. }
  25972. ~ScopedSSLServer() {
  25973. svr_.stop();
  25974. if (th_.joinable()) { th_.join(); }
  25975. }
  25976. SSLServer &svr() { return svr_; }
  25977. int port() const { return port_; }
  25978. void listen() {
  25979. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25980. svr_.wait_until_ready();
  25981. }
  25982. private:
  25983. SSLServer svr_;
  25984. std::thread th_;
  25985. int port_ = 0;
  25986. };
  25987. // Sends one request through the CONNECT proxy to the TLS origin with a
  25988. // credential configured for each hop, and checks that each credential reaches
  25989. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25990. // origin's (every header in origin_headers) on the tunnelled request.
  25991. void CredentialsStayWithTheirHop(
  25992. const std::function<void(SSLClient &)> &set_credentials,
  25993. const std::string &scheme,
  25994. const std::vector<std::string> &origin_headers = {"Authorization"},
  25995. bool stream = false) {
  25996. std::atomic<int> origin_hits{0};
  25997. std::atomic<bool> origin_saw_proxy_authz{false};
  25998. std::atomic<bool> origin_saw_headers{false};
  25999. ScopedSSLServer origin;
  26000. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26001. origin_hits++;
  26002. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26003. origin_saw_headers =
  26004. std::all_of(origin_headers.begin(), origin_headers.end(),
  26005. [&](const std::string &h) { return req.has_header(h); });
  26006. res.set_content("ok", "text/plain");
  26007. });
  26008. origin.listen();
  26009. ScopedConnectProxy proxy(origin.port());
  26010. ASSERT_NE(0, proxy.port());
  26011. // Pinned to 127.0.0.1 for the same reason as the test below.
  26012. SSLClient cli("127.0.0.1", origin.port());
  26013. cli.enable_server_certificate_verification(false);
  26014. cli.set_proxy("127.0.0.1", proxy.port());
  26015. set_credentials(cli);
  26016. if (stream) {
  26017. auto handle = cli.open_stream("GET", "/x");
  26018. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26019. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26020. } else {
  26021. auto res = cli.Get("/x");
  26022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26023. EXPECT_EQ(StatusCode::OK_200, res->status);
  26024. }
  26025. EXPECT_EQ(1, origin_hits.load());
  26026. EXPECT_EQ(1, proxy.connect_hits());
  26027. EXPECT_TRUE(origin_saw_headers.load());
  26028. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26029. << "Proxy-Authorization must not be sent inside the tunnel";
  26030. auto connect_req = proxy.connect_request();
  26031. EXPECT_NE(std::string::npos,
  26032. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26033. for (const auto &h : origin_headers) {
  26034. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26035. << h << " must not be sent to the proxy on CONNECT";
  26036. }
  26037. }
  26038. } // namespace proxy_tunnel_test
  26039. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26040. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26041. [](SSLClient &cli) {
  26042. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26043. cli.set_basic_auth("origin-user", "origin-pass");
  26044. },
  26045. "Basic");
  26046. }
  26047. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26048. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26049. [](SSLClient &cli) {
  26050. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26051. cli.set_basic_auth("origin-user", "origin-pass");
  26052. },
  26053. "Basic", {"Authorization"}, true);
  26054. }
  26055. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26056. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26057. [](SSLClient &cli) {
  26058. cli.set_proxy_bearer_token_auth("proxy-token");
  26059. cli.set_bearer_token_auth("origin-token");
  26060. },
  26061. "Bearer");
  26062. }
  26063. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26064. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26065. [](SSLClient &cli) {
  26066. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26067. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26068. {"Cookie", "sid=origin-session"},
  26069. {"X-Api-Key", "origin-key"}});
  26070. },
  26071. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26072. }
  26073. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26074. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26075. // retry; otherwise proxy creds would be sent to the origin.
  26076. std::atomic<int> origin_hits{0};
  26077. std::atomic<bool> origin_saw_proxy_authz{false};
  26078. proxy_tunnel_test::ScopedSSLServer origin;
  26079. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26080. origin_hits++;
  26081. if (req.has_header("Proxy-Authorization")) {
  26082. origin_saw_proxy_authz = true;
  26083. }
  26084. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26085. res.set_header("Proxy-Authenticate",
  26086. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26087. "algorithm=MD5");
  26088. });
  26089. origin.listen();
  26090. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26091. ASSERT_NE(0, proxy.port());
  26092. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26093. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26094. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26095. // and answer with its own status, making this test flaky.
  26096. SSLClient cli("127.0.0.1", origin.port());
  26097. cli.enable_server_certificate_verification(false);
  26098. cli.set_proxy("127.0.0.1", proxy.port());
  26099. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26100. auto res = cli.Get("/x");
  26101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26102. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26103. EXPECT_EQ(1, origin_hits.load());
  26104. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26105. EXPECT_EQ(1, proxy.connect_hits());
  26106. }
  26107. #endif
  26108. namespace proxy_tunnel_test {
  26109. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26110. // anything else gets a 407 with `challenge`.
  26111. ConnectReply require_proxy_auth(const std::string &expected,
  26112. const std::string &challenge) {
  26113. return [=](const std::string &head) -> std::string {
  26114. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26115. std::string::npos) {
  26116. return kTunnelEstablished;
  26117. }
  26118. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26119. "Proxy-Authenticate: " +
  26120. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26121. };
  26122. }
  26123. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26124. // request, then echoes.
  26125. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26126. ws.send(
  26127. "authorization:" + req.get_header_value("Authorization") +
  26128. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26129. std::string msg;
  26130. while (ws.read(msg)) {
  26131. ws.send(msg);
  26132. }
  26133. }
  26134. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26135. class ScopedWebSocketOrigin {
  26136. public:
  26137. ScopedWebSocketOrigin() {
  26138. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26139. server_.listen();
  26140. }
  26141. int port() const { return server_.port(); }
  26142. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26143. std::string url() const {
  26144. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26145. }
  26146. private:
  26147. no_proxy_test::ScopedServer server_;
  26148. };
  26149. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26150. // passed as a constructor header, and checks that each reaches only its hop.
  26151. void WebSocketCredentialsStayWithTheirHop(
  26152. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26153. const std::string &proxy_authz, const std::string &origin_authz) {
  26154. ScopedWebSocketOrigin origin;
  26155. ScopedConnectProxy proxy(
  26156. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26157. ASSERT_NE(0, proxy.port());
  26158. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26159. client.set_proxy("127.0.0.1", proxy.port());
  26160. set_proxy_credentials(client);
  26161. auto res = client.connect();
  26162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26163. std::string msg;
  26164. ASSERT_TRUE(client.read(msg));
  26165. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26166. client.close();
  26167. EXPECT_EQ(1, proxy.connect_hits());
  26168. EXPECT_EQ(std::string::npos,
  26169. proxy.connect_request().find("\r\nAuthorization: "))
  26170. << "origin credentials must not be sent to the proxy";
  26171. }
  26172. } // namespace proxy_tunnel_test
  26173. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26174. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26175. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26176. ASSERT_NE(0, proxy.port());
  26177. ws::WebSocketClient client(origin.url());
  26178. client.set_proxy("127.0.0.1", proxy.port());
  26179. auto res = client.connect();
  26180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26181. std::string msg;
  26182. ASSERT_TRUE(client.read(msg));
  26183. ASSERT_TRUE(client.send("hello"));
  26184. ASSERT_TRUE(client.read(msg));
  26185. EXPECT_EQ("hello", msg);
  26186. client.close();
  26187. EXPECT_EQ(1, proxy.connect_hits());
  26188. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26189. auto connect_req = proxy.connect_request();
  26190. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26191. EXPECT_NE(std::string::npos,
  26192. connect_req.find("\r\nHost: " + target + "\r\n"));
  26193. }
  26194. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26195. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26196. [](ws::WebSocketClient &cli) {
  26197. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26198. },
  26199. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26200. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26201. }
  26202. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26203. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26204. [](ws::WebSocketClient &cli) {
  26205. cli.set_proxy_bearer_token_auth("proxy-token");
  26206. },
  26207. "Bearer proxy-token", "Bearer origin-token");
  26208. }
  26209. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26210. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26211. proxy_tunnel_test::ScopedConnectProxy proxy(
  26212. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26213. "Basic " + detail::base64_encode("proxy-user:"),
  26214. "Basic realm=\"proxy\""));
  26215. ASSERT_NE(0, proxy.port());
  26216. ws::WebSocketClient client(origin.url());
  26217. client.set_proxy("127.0.0.1", proxy.port());
  26218. client.set_proxy_basic_auth("proxy-user", "");
  26219. auto res = client.connect();
  26220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26221. client.close();
  26222. EXPECT_EQ(1, proxy.connect_hits());
  26223. }
  26224. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26225. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26226. proxy_tunnel_test::ScopedConnectProxy proxy(
  26227. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26228. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26229. ASSERT_NE(0, proxy.port());
  26230. ws::WebSocketClient client(origin.url());
  26231. client.set_proxy("127.0.0.1", proxy.port());
  26232. auto res = client.connect();
  26233. EXPECT_FALSE(res);
  26234. EXPECT_EQ(Error::ProxyConnection, res.error());
  26235. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26236. EXPECT_EQ("Basic realm=\"proxy\"",
  26237. res.get_header_value("Proxy-Authenticate"));
  26238. EXPECT_FALSE(client.is_open());
  26239. }
  26240. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26241. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26242. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26243. ASSERT_NE(0, proxy.port());
  26244. ws::WebSocketClient client(origin.url());
  26245. client.set_proxy("127.0.0.1", proxy.port());
  26246. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26247. client.set_no_proxy({"127.0.0.1"});
  26248. auto res = client.connect();
  26249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26250. std::string msg;
  26251. ASSERT_TRUE(client.read(msg));
  26252. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26253. << "proxy credentials must not reach a bypassed origin";
  26254. client.close();
  26255. EXPECT_EQ(0, proxy.connect_hits());
  26256. }
  26257. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26258. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26259. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26260. ASSERT_NE(0, proxy.port());
  26261. ws::WebSocketClient client(origin.url());
  26262. client.set_proxy("127.0.0.1", proxy.port());
  26263. ASSERT_TRUE(client.connect());
  26264. ASSERT_TRUE(client.connect());
  26265. client.close();
  26266. EXPECT_EQ(2, proxy.connect_hits());
  26267. }
  26268. #ifdef CPPHTTPLIB_SSL_ENABLED
  26269. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26270. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26271. proxy_tunnel_test::ScopedConnectProxy proxy(
  26272. origin.port(), [](const std::string &head) -> std::string {
  26273. if (head.find(
  26274. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26275. std::string::npos) {
  26276. return proxy_tunnel_test::kTunnelEstablished;
  26277. }
  26278. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26279. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26280. "nonce=\"abc\", algorithm=MD5\r\n"
  26281. "Content-Length: 0\r\n\r\n";
  26282. });
  26283. ASSERT_NE(0, proxy.port());
  26284. ws::WebSocketClient client(origin.url());
  26285. client.set_proxy("127.0.0.1", proxy.port());
  26286. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26287. auto res = client.connect();
  26288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26289. std::string msg;
  26290. ASSERT_TRUE(client.read(msg));
  26291. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26292. client.close();
  26293. EXPECT_EQ(2, proxy.connect_hits());
  26294. }
  26295. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26296. proxy_tunnel_test::ScopedSSLServer origin;
  26297. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26298. origin.listen();
  26299. proxy_tunnel_test::ScopedConnectProxy proxy(
  26300. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26301. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26302. ASSERT_NE(0, proxy.port());
  26303. ws::WebSocketClient client(
  26304. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26305. client.enable_server_certificate_verification(false);
  26306. client.set_proxy("127.0.0.1", proxy.port());
  26307. client.set_proxy_bearer_token_auth("proxy-token");
  26308. auto res = client.connect();
  26309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26310. std::string msg;
  26311. ASSERT_TRUE(client.read(msg));
  26312. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26313. << "Proxy-Authorization must not be sent inside the tunnel";
  26314. client.close();
  26315. EXPECT_EQ(1, proxy.connect_hits());
  26316. }
  26317. #endif