test.cc 1022 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2318. auto host = "unresolvableaddress.local";
  2319. auto path = std::string{"/"};
  2320. #ifdef CPPHTTPLIB_SSL_ENABLED
  2321. auto port = 443;
  2322. SSLClient cli(host, port);
  2323. #else
  2324. auto port = 80;
  2325. Client cli(host, port);
  2326. #endif
  2327. cli.set_connection_timeout(1);
  2328. {
  2329. auto res = cli.Get(path);
  2330. ASSERT_FALSE(res);
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. }
  2334. #if defined(__linux__) && defined(__GLIBC__) && \
  2335. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2336. // Forward declaration: in split builds split.py strips `inline` and moves the
  2337. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2338. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2339. // against the symbol in both header-only and split builds.
  2340. namespace httplib {
  2341. namespace detail {
  2342. int getaddrinfo_with_timeout(const char *node, const char *service,
  2343. const struct addrinfo *hints,
  2344. struct addrinfo **res, time_t timeout_sec);
  2345. } // namespace detail
  2346. } // namespace httplib
  2347. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2348. //
  2349. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2350. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2351. // gai_suspend() call hits the connection timeout the function calls
  2352. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2353. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2354. // still alive and still references the now-destroyed stack frame.
  2355. //
  2356. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2357. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2358. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2359. // and runs them in a container.
  2360. namespace {
  2361. bool should_run_issue_2431_tests() {
  2362. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2363. return v && *v && std::string(v) != "0";
  2364. }
  2365. std::string unique_unresolvable_host(int n) {
  2366. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2367. // glibc still asks the configured nameserver — which is exactly the path
  2368. // we want to exercise. A unique label per call avoids the resolver cache.
  2369. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2370. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2371. std::to_string(n) + ".invalid";
  2372. }
  2373. } // namespace
  2374. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2375. if (!should_run_issue_2431_tests()) {
  2376. GTEST_SKIP()
  2377. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2378. }
  2379. for (int i = 0; i < 8; ++i) {
  2380. struct addrinfo hints;
  2381. memset(&hints, 0, sizeof(hints));
  2382. hints.ai_family = AF_UNSPEC;
  2383. hints.ai_socktype = SOCK_STREAM;
  2384. auto host = unique_unresolvable_host(i);
  2385. struct addrinfo *result = nullptr;
  2386. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2387. &result, /*timeout_sec=*/1);
  2388. if (rc == 0 && result) { freeaddrinfo(result); }
  2389. }
  2390. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2391. // stack region they still believe holds their gaicb.
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2395. if (!should_run_issue_2431_tests()) {
  2396. GTEST_SKIP()
  2397. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2398. }
  2399. std::atomic<bool> stop{false};
  2400. std::vector<std::thread> threads;
  2401. for (int t = 0; t < 8; ++t) {
  2402. threads.emplace_back([t, &stop] {
  2403. int i = 0;
  2404. while (!stop.load(std::memory_order_relaxed)) {
  2405. struct addrinfo hints;
  2406. memset(&hints, 0, sizeof(hints));
  2407. hints.ai_family = AF_UNSPEC;
  2408. hints.ai_socktype = SOCK_STREAM;
  2409. auto host = unique_unresolvable_host(t * 100000 + i++);
  2410. struct addrinfo *result = nullptr;
  2411. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2412. &result, /*timeout_sec=*/1);
  2413. if (rc == 0 && result) { freeaddrinfo(result); }
  2414. }
  2415. });
  2416. }
  2417. std::this_thread::sleep_for(std::chrono::seconds(8));
  2418. stop.store(true, std::memory_order_relaxed);
  2419. for (auto &th : threads) {
  2420. th.join();
  2421. }
  2422. std::this_thread::sleep_for(std::chrono::seconds(3));
  2423. }
  2424. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2425. if (!should_run_issue_2431_tests()) {
  2426. GTEST_SKIP()
  2427. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2428. }
  2429. std::atomic<bool> stop{false};
  2430. std::vector<std::thread> threads;
  2431. for (int t = 0; t < 8; ++t) {
  2432. threads.emplace_back([t, &stop] {
  2433. int i = 0;
  2434. while (!stop.load(std::memory_order_relaxed)) {
  2435. auto host = unique_unresolvable_host(t * 100000 + i++);
  2436. Client cli(host, 80);
  2437. cli.set_connection_timeout(1, 0);
  2438. cli.set_read_timeout(1, 0);
  2439. cli.set_write_timeout(1, 0);
  2440. (void)cli.Get("/");
  2441. }
  2442. });
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(8));
  2445. stop.store(true, std::memory_order_relaxed);
  2446. for (auto &th : threads) {
  2447. th.join();
  2448. }
  2449. std::this_thread::sleep_for(std::chrono::seconds(3));
  2450. }
  2451. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2452. TEST(ConnectionErrorTest, InvalidHost) {
  2453. auto host = "-abcde.com";
  2454. #ifdef CPPHTTPLIB_SSL_ENABLED
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. #else
  2458. auto port = 80;
  2459. Client cli(host, port);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. EXPECT_EQ(Error::Connection, res.error());
  2465. }
  2466. TEST(ConnectionErrorTest, InvalidHost2) {
  2467. auto host = "httpcan.org/";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. stringstream s;
  2489. s << "error code: " << res.error();
  2490. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2491. }
  2492. TEST(ConnectionErrorTest, InvalidPort) {
  2493. auto host = "localhost";
  2494. auto port = 44380;
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host, port);
  2497. #else
  2498. Client cli(host, port);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. EXPECT_TRUE(Error::Connection == res.error() ||
  2504. Error::ConnectionTimeout == res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, Timeout_Online) {
  2507. auto host = "google.com";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. auto port = 44380;
  2510. SSLClient cli(host, port);
  2511. #else
  2512. auto port = 8080;
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. // only probe one address type so that the error reason
  2517. // correlates to the timed-out IPv4, not the unsupported
  2518. // IPv6 connection attempt
  2519. cli.set_address_family(AF_INET);
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2523. }
  2524. TEST(CancelTest, NoCancel_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/range/32"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. auto port = 443;
  2529. SSLClient cli(host, port);
  2530. #else
  2531. auto port = 80;
  2532. Client cli(host, port);
  2533. #endif
  2534. cli.set_connection_timeout(std::chrono::seconds(5));
  2535. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. }
  2540. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2541. // Use /bytes with a large payload so that the DownloadProgress callback
  2542. // (which only fires for Content-Length responses) is invoked before the
  2543. // entire body is received, giving cancellation a chance to fire.
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/bytes/524288"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2554. cli.set_connection_timeout(std::chrono::seconds(5));
  2555. ASSERT_TRUE(!res);
  2556. EXPECT_EQ(Error::Canceled, res.error());
  2557. }
  2558. TEST(CancelTest, WithCancelLargePayload_Online) {
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(5));
  2569. uint32_t count = 0;
  2570. auto res =
  2571. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_EQ(Error::Canceled, res.error());
  2574. }
  2575. TEST(CancelTest, NoCancelPost) {
  2576. Server svr;
  2577. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_connection_timeout(std::chrono::seconds(5));
  2589. auto res =
  2590. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2591. "application/json", [](uint64_t, uint64_t) { return true; });
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ("Hello World!", res->body);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. }
  2596. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2597. Server svr;
  2598. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return false; });
  2613. ASSERT_TRUE(!res);
  2614. EXPECT_EQ(Error::Canceled, res.error());
  2615. }
  2616. TEST(CancelTest, WithCancelLargePayloadPost) {
  2617. Server svr;
  2618. svr.set_payload_max_length(200 * 1024 * 1024);
  2619. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content(LARGE_DATA, "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_payload_max_length(200 * 1024 * 1024);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, NoCancelPut) {
  2639. Server svr;
  2640. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_connection_timeout(std::chrono::seconds(5));
  2652. auto res =
  2653. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2654. "application/json", [](uint64_t, uint64_t) { return true; });
  2655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2656. EXPECT_EQ("Hello World!", res->body);
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2660. Server svr;
  2661. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return false; });
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Canceled, res.error());
  2678. }
  2679. TEST(CancelTest, WithCancelLargePayloadPut) {
  2680. Server svr;
  2681. svr.set_payload_max_length(200 * 1024 * 1024);
  2682. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content(LARGE_DATA, "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_payload_max_length(200 * 1024 * 1024);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, NoCancelPatch) {
  2702. Server svr;
  2703. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_connection_timeout(std::chrono::seconds(5));
  2715. auto res =
  2716. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2717. "application/json", [](uint64_t, uint64_t) { return true; });
  2718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2719. EXPECT_EQ("Hello World!", res->body);
  2720. EXPECT_EQ(StatusCode::OK_200, res->status);
  2721. }
  2722. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2723. Server svr;
  2724. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. });
  2727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2728. auto se = detail::scope_exit([&] {
  2729. svr.stop();
  2730. thread.join();
  2731. ASSERT_FALSE(svr.is_running());
  2732. });
  2733. svr.wait_until_ready();
  2734. Client cli(HOST, PORT);
  2735. cli.set_connection_timeout(std::chrono::seconds(5));
  2736. auto res =
  2737. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2738. "application/json", [](uint64_t, uint64_t) { return false; });
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Canceled, res.error());
  2741. }
  2742. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2743. Server svr;
  2744. svr.set_payload_max_length(200 * 1024 * 1024);
  2745. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2746. res.set_content(LARGE_DATA, "text/plain");
  2747. });
  2748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2749. auto se = detail::scope_exit([&] {
  2750. svr.stop();
  2751. thread.join();
  2752. ASSERT_FALSE(svr.is_running());
  2753. });
  2754. svr.wait_until_ready();
  2755. Client cli(HOST, PORT);
  2756. cli.set_payload_max_length(200 * 1024 * 1024);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, NoCancelDelete) {
  2765. Server svr;
  2766. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!", "text/plain");
  2768. });
  2769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2770. auto se = detail::scope_exit([&] {
  2771. svr.stop();
  2772. thread.join();
  2773. ASSERT_FALSE(svr.is_running());
  2774. });
  2775. svr.wait_until_ready();
  2776. Client cli(HOST, PORT);
  2777. cli.set_connection_timeout(std::chrono::seconds(5));
  2778. auto res =
  2779. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2780. "application/json", [](uint64_t, uint64_t) { return true; });
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ("Hello World!", res->body);
  2783. EXPECT_EQ(StatusCode::OK_200, res->status);
  2784. }
  2785. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2786. Server svr;
  2787. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2788. res.set_content("Hello World!", "text/plain");
  2789. });
  2790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. Client cli(HOST, PORT);
  2798. cli.set_connection_timeout(std::chrono::seconds(5));
  2799. auto res =
  2800. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2801. "application/json", [](uint64_t, uint64_t) { return false; });
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2806. Server svr;
  2807. svr.set_payload_max_length(200 * 1024 * 1024);
  2808. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2809. res.set_content(LARGE_DATA, "text/plain");
  2810. });
  2811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2812. auto se = detail::scope_exit([&] {
  2813. svr.stop();
  2814. thread.join();
  2815. ASSERT_FALSE(svr.is_running());
  2816. });
  2817. svr.wait_until_ready();
  2818. Client cli(HOST, PORT);
  2819. cli.set_payload_max_length(200 * 1024 * 1024);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. static std::string remove_whitespace(const std::string &input) {
  2828. std::string output;
  2829. output.reserve(input.size());
  2830. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2831. [](unsigned char c) { return !std::isspace(c); });
  2832. return output;
  2833. }
  2834. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2835. auto host = "httpbingo.org";
  2836. auto path = std::string{"/basic-auth/hello/world"};
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. auto port = 443;
  2839. SSLClient cli(host, port);
  2840. #else
  2841. auto port = 80;
  2842. Client cli(host, port);
  2843. #endif
  2844. {
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. auto res = cli.Get(
  2851. path, Headers{make_basic_authentication_header("hello", "world")});
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. auto body = remove_whitespace(res->body);
  2854. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2855. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. }
  2858. {
  2859. cli.set_basic_auth("hello", "world");
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. auto body = remove_whitespace(res->body);
  2863. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2864. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. {
  2868. cli.set_basic_auth("hello", "bad");
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("bad", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2878. }
  2879. }
  2880. #ifdef CPPHTTPLIB_SSL_ENABLED
  2881. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2882. auto host = "httpbingo.org";
  2883. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2884. auto paths = std::vector<std::string>{
  2885. "/digest-auth/auth/hello/world/MD5",
  2886. "/digest-auth/auth/hello/world/SHA-256",
  2887. };
  2888. auto port = 443;
  2889. SSLClient cli(host, port);
  2890. {
  2891. auto res = cli.Get(unauth_path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_digest_auth("hello", "world");
  2897. for (const auto &path : paths) {
  2898. auto res = cli.Get(path.c_str());
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. auto body = remove_whitespace(res->body);
  2901. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2902. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. cli.set_digest_auth("hello", "bad");
  2906. for (const auto &path : paths) {
  2907. auto res = cli.Get(path.c_str());
  2908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2909. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2910. }
  2911. }
  2912. }
  2913. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2914. // comma-separated list of challenges, and each challenge may itself carry a
  2915. // comma-separated auth-param list, so a server can legally offer Basic
  2916. // before Digest, either as two field lines or packed into one. Runs one 401
  2917. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2918. // value() joins them in receipt order) and checks that the retry carries a
  2919. // well-formed Digest Authorization header naming expected_realm.
  2920. static void
  2921. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2922. const std::string &expected_realm) {
  2923. std::atomic<int> hits{0};
  2924. Server svr;
  2925. svr.Get("/x", [&](const Request &req, Response &res) {
  2926. if (++hits == 1) {
  2927. res.status = StatusCode::Unauthorized_401;
  2928. for (const auto &challenge : challenges) {
  2929. res.set_header("WWW-Authenticate", challenge);
  2930. }
  2931. } else {
  2932. auto authorization = req.get_header_value("Authorization");
  2933. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2934. EXPECT_NE(std::string::npos,
  2935. authorization.find("realm=\"" + expected_realm + "\""));
  2936. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2937. res.set_content("ok", "text/plain");
  2938. }
  2939. });
  2940. auto port = svr.bind_to_any_port(HOST);
  2941. std::thread t([&]() { svr.listen_after_bind(); });
  2942. auto se = detail::scope_exit([&] {
  2943. svr.stop();
  2944. t.join();
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, port);
  2948. cli.set_digest_auth("hello", "world");
  2949. auto res = cli.Get("/x");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(2, hits.load());
  2952. }
  2953. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2954. static const char *kDigestChallenge =
  2955. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2956. "algorithm=MD5";
  2957. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2958. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2959. "testrealm");
  2960. }
  2961. // Same challenge list with the schemes in the opposite order, to make sure
  2962. // the fix above didn't just special-case "Basic first".
  2963. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2964. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2965. "testrealm");
  2966. }
  2967. // A comma inside a quoted auth-param value must not be mistaken for the
  2968. // separator between two challenges (or two auth-params).
  2969. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2970. run_digest_challenge_list_test(
  2971. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2972. "algorithm=MD5"},
  2973. "test,realm");
  2974. }
  2975. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2976. // the params and leaves out the fragment.
  2977. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2978. Server svr;
  2979. std::string uri, target;
  2980. svr.Get("/a b", [&](const Request &req, Response &res) {
  2981. auto auth = req.get_header_value("Authorization");
  2982. if (auth.empty()) {
  2983. res.status = StatusCode::Unauthorized_401;
  2984. res.set_header("WWW-Authenticate",
  2985. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2986. return;
  2987. }
  2988. auto b = auth.find("uri=\"") + 5;
  2989. uri = auth.substr(b, auth.find('"', b) - b);
  2990. target = req.target;
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("/a%20b?x=1", target);
  3004. EXPECT_EQ(target, uri);
  3005. }
  3006. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3007. // make_digest_authentication_header() dereferences both unconditionally, so
  3008. // a server sending a challenge missing either one must not be treated as
  3009. // usable -- doing so used to crash the client with std::out_of_range.
  3010. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3011. Server svr;
  3012. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3013. res.status = StatusCode::Unauthorized_401;
  3014. res.set_header("WWW-Authenticate", challenge);
  3015. });
  3016. auto port = svr.bind_to_any_port(HOST);
  3017. std::thread t([&]() { svr.listen_after_bind(); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. t.join();
  3021. });
  3022. svr.wait_until_ready();
  3023. Client cli(HOST, port);
  3024. cli.set_digest_auth("hello", "world");
  3025. auto res = cli.Get("/x");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3028. }
  3029. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3030. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3031. }
  3032. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3033. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3034. }
  3035. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3036. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3037. }
  3038. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3039. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3040. // when storing the values, so the header builder has to re-escape them (and
  3041. // keep algorithm a bare token); otherwise the value breaks out of its
  3042. // quoted-string and injects extra auth-params into the client's Authorization.
  3043. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3044. std::atomic<int> hits{0};
  3045. std::string authorization;
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request &req, Response &res) {
  3048. if (++hits == 1) {
  3049. res.status = StatusCode::Unauthorized_401;
  3050. // On the wire the quotes embedded in the values are backslash-escaped.
  3051. res.set_header("WWW-Authenticate",
  3052. "Digest realm=\"testrealm\", "
  3053. "nonce=\"n\\\"; injected=\\\"x\", "
  3054. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3055. } else {
  3056. authorization = req.get_header_value("Authorization");
  3057. res.set_content("ok", "text/plain");
  3058. }
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. std::thread t([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. t.join();
  3065. });
  3066. svr.wait_until_ready();
  3067. Client cli(HOST, port);
  3068. cli.set_digest_auth("hello", "world");
  3069. auto res = cli.Get("/x");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. EXPECT_EQ(2, hits.load());
  3072. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3073. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3074. // inside its quoted-string rather than starting an "injected" auth-param.
  3075. EXPECT_NE(std::string::npos,
  3076. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3077. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3078. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3079. }
  3080. #endif
  3081. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3082. auto host = "google.com";
  3083. auto another_host = "example.com";
  3084. auto wrong_ip = "0.0.0.0";
  3085. #ifdef CPPHTTPLIB_SSL_ENABLED
  3086. SSLClient cli(host);
  3087. #else
  3088. Client cli(host);
  3089. #endif
  3090. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3091. auto res = cli.Get("/");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3094. }
  3095. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3096. auto host = "google.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(!res);
  3106. EXPECT_EQ(Error::Connection, res.error());
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3109. // A mapped value that is not an IP literal must be resolved. "localhost"
  3110. // resolves from the hosts file, so this test needs no external DNS.
  3111. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3112. auto host = "target.invalid";
  3113. Server svr;
  3114. std::string received_host;
  3115. svr.Get("/hi", [&](const Request &req, Response &res) {
  3116. received_host = req.get_header_value("Host");
  3117. res.set_content("Hello World!", "text/plain");
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. Client cli(host, port);
  3128. cli.set_hostname_addr_map({{host, HOST}});
  3129. auto res = cli.Get("/hi");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. // The mapping only redirects the connection; the identity stays host_.
  3133. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3134. }
  3135. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3136. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3137. auto host = "target.invalid";
  3138. Server svr;
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. });
  3142. auto port = svr.bind_to_any_port("127.0.0.1");
  3143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. Client cli(host, port);
  3151. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3152. auto res = cli.Get("/hi");
  3153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. }
  3156. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3157. // An empty mapped value must leave host_ as the connection target. Without
  3158. // that guard the empty value would become the host argument, getaddrinfo
  3159. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3160. // loopback - silently connecting somewhere the caller never asked for.
  3161. // The server listens on loopback, so such a fallback would succeed and is
  3162. // therefore observable as a failure of this test.
  3163. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3164. Server svr;
  3165. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3166. res.set_content("Hello World!", "text/plain");
  3167. });
  3168. auto port = svr.bind_to_any_port(HOST);
  3169. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. Client cli(blackhole, port);
  3177. cli.set_hostname_addr_map({{blackhole, ""}});
  3178. cli.set_connection_timeout(1);
  3179. auto res = cli.Get("/hi");
  3180. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3181. }
  3182. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3183. auto host = "httpbingo.org";
  3184. auto path = std::string{"/absolute-redirect/3"};
  3185. #ifdef CPPHTTPLIB_SSL_ENABLED
  3186. SSLClient cli(host);
  3187. #else
  3188. Client cli(host);
  3189. #endif
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get(path);
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. }
  3195. TEST(RedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RelativeRedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/relative-redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(TooManyRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/redirect/21"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(!res);
  3232. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3233. }
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. TEST(YahooRedirectTest, Redirect_Online) {
  3236. Client cli("yahoo.com");
  3237. auto res = cli.Get("/");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3240. cli.set_follow_location(true);
  3241. res = cli.Get("/");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3245. }
  3246. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3247. #define REDIR_HOST "httpbingo.org"
  3248. #define REDIR_PATH "/redirect-to"
  3249. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3250. SSLClient cli(REDIR_HOST);
  3251. cli.set_follow_location(true);
  3252. auto res =
  3253. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3258. SSLClient cli(REDIR_HOST);
  3259. cli.set_follow_location(true);
  3260. Params params;
  3261. params.emplace("url", "http://example.com");
  3262. params.emplace("status_code", "302");
  3263. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3268. SSLClient cli(REDIR_HOST);
  3269. cli.set_follow_location(true);
  3270. Params params;
  3271. params.emplace("url", "http://example.com");
  3272. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. }
  3276. TEST(UrlWithSpace, Redirect_Online) {
  3277. SSLClient cli("edge.forgecdn.net");
  3278. cli.set_follow_location(true);
  3279. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3281. EXPECT_EQ(StatusCode::OK_200, res->status);
  3282. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3283. }
  3284. #endif
  3285. #if !defined(_WIN32) && !defined(_WIN64)
  3286. TEST(ReceiveSignals, Signal) {
  3287. auto setupSignalHandlers = []() {
  3288. struct sigaction act;
  3289. sigemptyset(&act.sa_mask);
  3290. act.sa_flags = SA_SIGINFO;
  3291. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3292. switch (sig) {
  3293. case SIGINT:
  3294. default: break;
  3295. }
  3296. };
  3297. ::sigaction(SIGINT, &act, nullptr);
  3298. };
  3299. Server svr;
  3300. int port = 0;
  3301. auto thread = std::thread([&]() {
  3302. setupSignalHandlers();
  3303. port = svr.bind_to_any_port(HOST);
  3304. svr.listen_after_bind();
  3305. });
  3306. auto se = detail::scope_exit([&] {
  3307. svr.stop();
  3308. thread.join();
  3309. ASSERT_FALSE(svr.is_running());
  3310. });
  3311. svr.wait_until_ready();
  3312. ASSERT_TRUE(svr.is_running());
  3313. pthread_kill(thread.native_handle(), SIGINT);
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3315. ASSERT_TRUE(svr.is_running());
  3316. }
  3317. #endif
  3318. TEST(RedirectToDifferentPort, Redirect) {
  3319. Server svr1;
  3320. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3321. res.set_content("Hello World!", "text/plain");
  3322. });
  3323. int svr1_port = 0;
  3324. auto thread1 = std::thread([&]() {
  3325. svr1_port = svr1.bind_to_any_port(HOST);
  3326. svr1.listen_after_bind();
  3327. });
  3328. Server svr2;
  3329. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3330. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3331. });
  3332. int svr2_port = 0;
  3333. auto thread2 = std::thread([&]() {
  3334. svr2_port = svr2.bind_to_any_port(HOST);
  3335. svr2.listen_after_bind();
  3336. });
  3337. auto se = detail::scope_exit([&] {
  3338. svr2.stop();
  3339. thread2.join();
  3340. svr1.stop();
  3341. thread1.join();
  3342. ASSERT_FALSE(svr2.is_running());
  3343. ASSERT_FALSE(svr1.is_running());
  3344. });
  3345. svr1.wait_until_ready();
  3346. svr2.wait_until_ready();
  3347. Client cli("localhost", svr2_port);
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/2");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("Hello World!", res->body);
  3353. }
  3354. // GET /redir on one server redirects to /target on another port, so the
  3355. // client follows it with a new client.
  3356. static Result
  3357. GetThroughRedirectToDifferentPort(Server::Handler target,
  3358. const std::function<void(Client &)> &setup,
  3359. const Headers &headers = Headers()) {
  3360. Server target_svr;
  3361. target_svr.Get("/target", target);
  3362. int target_port = 0;
  3363. auto target_thread = std::thread([&]() {
  3364. target_port = target_svr.bind_to_any_port(HOST);
  3365. target_svr.listen_after_bind();
  3366. });
  3367. Server origin_svr;
  3368. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3369. res.set_redirect(
  3370. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3371. });
  3372. int origin_port = 0;
  3373. auto origin_thread = std::thread([&]() {
  3374. origin_port = origin_svr.bind_to_any_port(HOST);
  3375. origin_svr.listen_after_bind();
  3376. });
  3377. auto se = detail::scope_exit([&] {
  3378. origin_svr.stop();
  3379. origin_thread.join();
  3380. target_svr.stop();
  3381. target_thread.join();
  3382. });
  3383. target_svr.wait_until_ready();
  3384. origin_svr.wait_until_ready();
  3385. Client cli("localhost", origin_port);
  3386. cli.set_follow_location(true);
  3387. setup(cli);
  3388. return cli.Get("/redir", headers);
  3389. }
  3390. static void
  3391. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3392. std::string captured_authorization;
  3393. auto result = GetThroughRedirectToDifferentPort(
  3394. [&](const Request &req, Response &res) {
  3395. captured_authorization = req.get_header_value("Authorization");
  3396. res.set_content("OK", "text/plain");
  3397. },
  3398. set_auth);
  3399. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3400. EXPECT_EQ(StatusCode::OK_200, result->status);
  3401. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3402. EXPECT_TRUE(captured_authorization.empty());
  3403. }
  3404. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3405. TestDoNotForwardCredentialsOnRedirect(
  3406. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3407. }
  3408. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3409. TestDoNotForwardCredentialsOnRedirect(
  3410. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3411. }
  3412. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3413. std::string captured_cookie;
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [&](const Request &req, Response &res) {
  3416. captured_cookie = req.get_header_value("Cookie");
  3417. res.set_content("OK", "text/plain");
  3418. },
  3419. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3420. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3421. EXPECT_EQ(StatusCode::OK_200, result->status);
  3422. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3423. EXPECT_TRUE(captured_cookie.empty());
  3424. }
  3425. TEST(RedirectToSamePort, ForwardCookie) {
  3426. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3427. // header so that ordinary session flows keep working.
  3428. Server svr;
  3429. std::string captured_cookie;
  3430. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3431. res.set_redirect("/target", 302);
  3432. });
  3433. svr.Get("/target", [&](const Request &req, Response &res) {
  3434. captured_cookie = req.get_header_value("Cookie");
  3435. res.set_content("OK", "text/plain");
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_follow_location(true);
  3447. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3448. auto res = cli.Get("/redir", headers);
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3452. }
  3453. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3454. std::string authorization;
  3455. std::string trace_id;
  3456. auto result = GetThroughRedirectToDifferentPort(
  3457. [&](const Request &req, Response &res) {
  3458. authorization = req.get_header_value("Authorization");
  3459. trace_id = req.get_header_value("X-Trace-Id");
  3460. res.set_content("OK", "text/plain");
  3461. },
  3462. [](Client &cli) {
  3463. cli.set_default_headers(
  3464. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3465. });
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Like a header given with the request, a default one goes along unless it
  3469. // carries credentials (RFC 9110 15.4).
  3470. EXPECT_TRUE(authorization.empty());
  3471. EXPECT_EQ("42", trace_id);
  3472. }
  3473. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3474. auto result = GetThroughRedirectToDifferentPort(
  3475. [](const Request &, Response &res) {
  3476. res.set_content(std::string(2048, 'x'), "text/plain");
  3477. },
  3478. [](Client &cli) { cli.set_payload_max_length(1024); });
  3479. EXPECT_FALSE(result);
  3480. }
  3481. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3482. auto result = GetThroughRedirectToDifferentPort(
  3483. [](const Request &req, Response &res) {
  3484. // Answer after a second, or once the client gives up.
  3485. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3487. }
  3488. res.set_content("late", "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3491. ASSERT_FALSE(result);
  3492. EXPECT_EQ(Error::Read, result.error());
  3493. }
  3494. #ifdef CPPHTTPLIB_SSL_ENABLED
  3495. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.status = StatusCode::Unauthorized_401;
  3499. res.set_header("WWW-Authenticate",
  3500. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3501. },
  3502. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3503. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3504. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3505. }
  3506. #endif
  3507. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3508. Server svr;
  3509. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3510. // Port number that overflows int — should not crash
  3511. res.set_redirect("http://localhost:99999999999999999999/target");
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. Client cli(HOST, port);
  3522. cli.set_follow_location(true);
  3523. auto res = cli.Get("/redir");
  3524. // Should fail gracefully, not crash (no valid response due to bad port)
  3525. EXPECT_FALSE(res);
  3526. }
  3527. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3528. Server svr;
  3529. auto port = svr.bind_to_any_port(HOST);
  3530. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3531. // The server's own port followed by junk must not be followed
  3532. res.set_redirect("http://" + std::string(HOST) + ":" +
  3533. std::to_string(port) + "junk/target");
  3534. });
  3535. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3536. res.set_content("target", "text/plain");
  3537. });
  3538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. thread.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. Client cli(HOST, port);
  3546. cli.set_follow_location(true);
  3547. auto res = cli.Get("/redir");
  3548. EXPECT_FALSE(res);
  3549. }
  3550. TEST(RedirectFromPageWithContent, Redirect) {
  3551. Server svr;
  3552. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("___", "text/plain");
  3554. res.set_redirect("/2");
  3555. });
  3556. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!", "text/plain");
  3558. });
  3559. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. th.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli("localhost", PORT);
  3568. cli.set_follow_location(true);
  3569. std::string body;
  3570. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3571. body.append(data, data_length);
  3572. return true;
  3573. });
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Hello World!", body);
  3577. }
  3578. {
  3579. Client cli("localhost", PORT);
  3580. std::string body;
  3581. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3582. body.append(data, data_length);
  3583. return true;
  3584. });
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::Found_302, res->status);
  3587. EXPECT_EQ("___", body);
  3588. }
  3589. }
  3590. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3591. Server svr;
  3592. auto port_str = std::to_string(PORT);
  3593. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3594. auto expected_host = "[::1]:" + port_str;
  3595. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3596. res.set_content("___", "text/plain");
  3597. // res.set_redirect("/2");
  3598. res.set_redirect(redirect_url);
  3599. });
  3600. svr.Get("/2", [&](const Request &req, Response &res) {
  3601. auto host_header = req.headers.find("Host");
  3602. ASSERT_TRUE(host_header != req.headers.end());
  3603. EXPECT_EQ(expected_host, host_header->second);
  3604. res.set_content("Hello World!", "text/plain");
  3605. });
  3606. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. th.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3613. // actually starts anything, so the condition !svr.is_running() will
  3614. // always remain true, and the loop never stops.
  3615. // This basically counts how many milliseconds have passed since the
  3616. // call to svr.listen(), and if after 5 seconds nothing started yet
  3617. // aborts the test.
  3618. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3620. ASSERT_LT(milliseconds, 5000U);
  3621. }
  3622. {
  3623. Client cli("::1", PORT);
  3624. cli.set_follow_location(true);
  3625. std::string body;
  3626. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3627. body.append(data, data_length);
  3628. return true;
  3629. });
  3630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("Hello World!", body);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::Found_302, res->status);
  3643. EXPECT_EQ("___", body);
  3644. }
  3645. }
  3646. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3647. Server svr;
  3648. svr.Get("/foo", [](const Request &req, Response &res) {
  3649. auto a = req.params.find("a");
  3650. if (a != req.params.end()) {
  3651. res.set_content((*a).second, "text/plain");
  3652. res.status = StatusCode::OK_200;
  3653. } else {
  3654. res.status = StatusCode::BadRequest_400;
  3655. }
  3656. });
  3657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. {
  3665. Client cli(HOST, PORT);
  3666. cli.set_path_encode(false);
  3667. auto res = cli.Get("/foo?a=explicitly+encoded");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. // This expects it back with a space, as the `+` won't have been
  3671. // url-encoded, and server-side the params get decoded turning `+`
  3672. // into spaces.
  3673. EXPECT_EQ("explicitly encoded", res->body);
  3674. }
  3675. }
  3676. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3677. // When path encoding is disabled the client must transmit the supplied
  3678. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3679. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3680. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3681. // than a space (0x20). Assert on the raw wire target to catch this.
  3682. Server svr;
  3683. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3684. svr.Get("/foo", [&](const Request &req, Response &res) {
  3685. EXPECT_EQ(expected_target, req.target);
  3686. res.status = StatusCode::OK_200;
  3687. });
  3688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, PORT);
  3697. cli.set_path_encode(false);
  3698. auto res = cli.Get(expected_target.c_str());
  3699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. }
  3703. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3704. // `open_stream()` used to skip the path encoding that the buffered send
  3705. // path applies, so the same `path` produced different bytes in the request
  3706. // line depending on which API was used. Assert the two agree.
  3707. Server svr;
  3708. std::string target;
  3709. svr.Get(".*", [&](const Request &req, Response &res) {
  3710. target = req.target;
  3711. res.status = StatusCode::OK_200;
  3712. });
  3713. auto port = svr.bind_to_any_port(HOST);
  3714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. struct {
  3722. const char *path;
  3723. const char *expected;
  3724. } cases[] = {
  3725. {"/a b?x=1", "/a%20b?x=1"},
  3726. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3727. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3728. };
  3729. for (const auto &c : cases) {
  3730. Client cli(HOST, port);
  3731. target.clear();
  3732. auto res = cli.Get(c.path);
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3735. auto buffered_target = target;
  3736. target.clear();
  3737. auto handle = cli.open_stream("GET", c.path);
  3738. EXPECT_TRUE(handle.is_valid())
  3739. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3740. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3744. // The `set_path_encode(false)` contract — transmit the supplied target
  3745. // verbatim — must hold for the streaming API too.
  3746. Server svr;
  3747. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3748. std::string target;
  3749. svr.Get("/foo", [&](const Request &req, Response &res) {
  3750. target = req.target;
  3751. res.status = StatusCode::OK_200;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. cli.set_path_encode(false);
  3764. auto handle = cli.open_stream("GET", expected_target);
  3765. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3766. EXPECT_EQ(expected_target, target);
  3767. }
  3768. }
  3769. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3770. // With path encoding enabled a CR/LF in the target is percent-encoded
  3771. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3772. // write_request_line still backstops `set_path_encode(false)`, which is
  3773. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3774. Server svr;
  3775. // Captured before routing: the decoded path contains a newline, which a
  3776. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3777. std::string target;
  3778. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3779. target = req.target;
  3780. res.status = StatusCode::OK_200;
  3781. return Server::HandlerResponse::Handled;
  3782. });
  3783. auto port = svr.bind_to_any_port(HOST);
  3784. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, port);
  3793. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3794. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3795. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3796. }
  3797. }
  3798. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3799. // Every control character is percent-encoded, not just CR/LF, so the target
  3800. // passes the request-target check in write_request_line.
  3801. Server svr;
  3802. std::string target;
  3803. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3804. target = req.target;
  3805. res.status = StatusCode::OK_200;
  3806. return Server::HandlerResponse::Handled;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/a\tb\x1b\x7f");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ("/a%09b%1B%7F", target);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3824. // Nothing may reach the wire: a raw CR/LF target would split the request
  3825. // line and inject headers.
  3826. Server svr;
  3827. // Pre-routing so that "not called" means nothing reached the server at all,
  3828. // rather than merely failing to match a handler pattern.
  3829. auto handler_called = false;
  3830. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3831. handler_called = true;
  3832. res.status = StatusCode::OK_200;
  3833. return Server::HandlerResponse::Handled;
  3834. });
  3835. auto port = svr.bind_to_any_port(HOST);
  3836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. {
  3844. Client cli(HOST, port);
  3845. cli.set_path_encode(false);
  3846. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3847. EXPECT_FALSE(handle.is_valid());
  3848. EXPECT_EQ(Error::Write, handle.error);
  3849. EXPECT_FALSE(handler_called);
  3850. }
  3851. }
  3852. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3853. // Which of the two branches runs is decided by whether the query component
  3854. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3855. // an empty query and must still fall back to building one from
  3856. // `req.params`, while a non-empty query must win over `req.params`.
  3857. Server svr;
  3858. std::string target;
  3859. svr.Get("/foo", [&](const Request &req, Response &res) {
  3860. target = req.target;
  3861. res.status = StatusCode::OK_200;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. // Trailing `?` -> empty query component -> `req.params` is used.
  3873. Client cli(HOST, port);
  3874. Request req;
  3875. req.method = "GET";
  3876. req.path = "/foo?";
  3877. req.params.emplace("a", "1");
  3878. target.clear();
  3879. auto res = cli.send(req);
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ("/foo?a=1", target);
  3882. }
  3883. {
  3884. // Non-empty query in `req.path` -> `req.params` is not appended.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?b=2";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?b=2", target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3897. Server svr;
  3898. svr.Get("/", [](const Request &req, Response &) {
  3899. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3900. });
  3901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3902. auto se = detail::scope_exit([&] {
  3903. svr.stop();
  3904. thread.join();
  3905. ASSERT_FALSE(svr.is_running());
  3906. });
  3907. svr.wait_until_ready();
  3908. {
  3909. Client cli(HOST, PORT);
  3910. cli.set_path_encode(false);
  3911. auto res = cli.Get("/?something=%0A");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. }
  3916. TEST(BindServerTest, BindDualStack) {
  3917. Server svr;
  3918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3919. res.set_content("Hello World!", "text/plain");
  3920. });
  3921. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3922. auto se = detail::scope_exit([&] {
  3923. svr.stop();
  3924. thread.join();
  3925. ASSERT_FALSE(svr.is_running());
  3926. });
  3927. svr.wait_until_ready();
  3928. {
  3929. Client cli("127.0.0.1", PORT);
  3930. auto res = cli.Get("/1");
  3931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3932. EXPECT_EQ(StatusCode::OK_200, res->status);
  3933. EXPECT_EQ("Hello World!", res->body);
  3934. }
  3935. {
  3936. Client cli("::1", PORT);
  3937. auto res = cli.Get("/1");
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("Hello World!", res->body);
  3941. }
  3942. }
  3943. TEST(BindServerTest, BindAndListenSeparately) {
  3944. Server svr;
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. svr.stop();
  3949. }
  3950. // Reports whether anything is still listening on a loopback port. A plain
  3951. // connect() is used instead of a Client request because a socket left bound by
  3952. // mistake accepts the connection into its backlog and never answers, which
  3953. // would hang the test instead of failing it.
  3954. static bool is_loopback_port_accepting(int port) {
  3955. sockaddr_in addr{};
  3956. addr.sin_family = AF_INET;
  3957. addr.sin_port = htons(static_cast<uint16_t>(port));
  3958. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3959. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3960. EXPECT_NE(sock, INVALID_SOCKET);
  3961. if (sock == INVALID_SOCKET) { return false; }
  3962. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3963. static_cast<socklen_t>(sizeof(addr)));
  3964. detail::close_socket(sock);
  3965. return ret == 0;
  3966. }
  3967. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3968. Server svr;
  3969. auto port = svr.bind_to_any_port("127.0.0.1");
  3970. ASSERT_TRUE(port > 0);
  3971. svr.stop();
  3972. // bind_to_any_port() already called listen(2), so until stop() closed the
  3973. // descriptor the port kept accepting connections into the backlog. ASSERT
  3974. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3975. // below blocks forever in the accept loop.
  3976. ASSERT_FALSE(is_loopback_port_accepting(port));
  3977. // Nothing is left to accept on, so listen_after_bind() must report failure
  3978. // instead of returning success without ever serving.
  3979. EXPECT_FALSE(svr.listen_after_bind());
  3980. // The failed listen marks the server decommissioned, so a waiter returns
  3981. // instead of spinning forever.
  3982. svr.wait_until_ready();
  3983. }
  3984. #ifdef CPPHTTPLIB_SSL_ENABLED
  3985. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3987. CLIENT_CA_CERT_DIR);
  3988. int port = svr.bind_to_any_port("0.0.0.0");
  3989. ASSERT_TRUE(svr.is_valid());
  3990. ASSERT_TRUE(port > 0);
  3991. svr.stop();
  3992. }
  3993. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3994. // or a rejected CustomRoute() registration would not stop the server binding.
  3995. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3997. CLIENT_CA_CERT_DIR);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4000. EXPECT_FALSE(svr.is_valid());
  4001. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4002. }
  4003. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4004. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4005. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4006. int port = svr.bind_to_any_port("0.0.0.0");
  4007. ASSERT_TRUE(svr.is_valid());
  4008. ASSERT_TRUE(port > 0);
  4009. svr.stop();
  4010. }
  4011. TEST(BindServerTest, UpdateCertsPem) {
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4013. int port = svr.bind_to_any_port("0.0.0.0");
  4014. ASSERT_TRUE(svr.is_valid());
  4015. ASSERT_TRUE(port > 0);
  4016. // Read PEM files
  4017. std::string cert_pem, key_pem, ca_pem;
  4018. read_file(SERVER_CERT_FILE, cert_pem);
  4019. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4020. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4021. // Update server certificates using PEM API
  4022. ASSERT_TRUE(
  4023. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4024. ASSERT_TRUE(svr.is_valid());
  4025. svr.stop();
  4026. }
  4027. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4028. // Start server with client CA (enables client auth)
  4029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4030. ASSERT_TRUE(svr.is_valid());
  4031. bool handler_called = false;
  4032. svr.Get("/test", [&](const Request &req, Response &res) {
  4033. handler_called = true;
  4034. // Verify client certificate is present
  4035. auto cert = req.peer_cert();
  4036. EXPECT_TRUE(static_cast<bool>(cert));
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // Read PEM files
  4047. std::string cert_pem, key_pem, ca_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4051. // Update server certificates and client CA using PEM API while server running
  4052. ASSERT_TRUE(
  4053. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4054. // Connect with client certificate
  4055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4056. cli.enable_server_certificate_verification(false);
  4057. cli.set_connection_timeout(30);
  4058. auto res = cli.Get("/test");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_TRUE(handler_called);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. // Puts a CA that did not sign the client's certificate in the old one's place.
  4065. static bool replace_client_ca(SSLServer &svr) {
  4066. std::string cert_pem, key_pem, ca_pem;
  4067. read_file(SERVER_CERT_FILE, cert_pem);
  4068. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4069. read_file(SERVER_CERT2_FILE, ca_pem);
  4070. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4071. ca_pem.c_str());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. auto get = [] {
  4087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4088. cli.enable_server_certificate_verification(false);
  4089. return cli.Get("/test");
  4090. };
  4091. ASSERT_TRUE(get());
  4092. ASSERT_TRUE(replace_client_ca(svr));
  4093. EXPECT_FALSE(get());
  4094. }
  4095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4096. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4098. ASSERT_TRUE(svr.is_valid());
  4099. tls::set_verify_callback(svr.tls_context(),
  4100. [](const tls::VerifyContext &) -> bool {
  4101. throw std::runtime_error("verify");
  4102. });
  4103. svr.Get("/test", [](const Request &, Response &res) {
  4104. res.set_content("ok", "text/plain");
  4105. });
  4106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4107. auto se = detail::scope_exit([&] {
  4108. svr.stop();
  4109. t.join();
  4110. ASSERT_FALSE(svr.is_running());
  4111. });
  4112. svr.wait_until_ready();
  4113. auto get = [] {
  4114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4115. cli.enable_server_certificate_verification(false);
  4116. return cli.Get("/test");
  4117. };
  4118. EXPECT_FALSE(get());
  4119. // The handshake is over, so an update does not wait for it.
  4120. std::string cert_pem, key_pem;
  4121. read_file(SERVER_CERT_FILE, cert_pem);
  4122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4123. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4124. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4125. return v.preverify_ok;
  4126. });
  4127. auto res = get();
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("ok", res->body);
  4130. }
  4131. #endif
  4132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4133. // Sends each request over a new connection with a client certificate,
  4134. // resuming the session of the one before when there is one.
  4135. class ResumingClient {
  4136. public:
  4137. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4138. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4139. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4140. SSL_FILETYPE_PEM);
  4141. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4142. // callback, not through SSL_get1_session().
  4143. SSL_CTX_set_app_data(ctx_, this);
  4144. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4145. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4146. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4147. auto self = static_cast<ResumingClient *>(
  4148. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4149. SSL_SESSION_free(self->session_);
  4150. self->session_ = session;
  4151. return 1; // Keeps the reference
  4152. });
  4153. }
  4154. ~ResumingClient() {
  4155. SSL_SESSION_free(session_);
  4156. SSL_CTX_free(ctx_);
  4157. }
  4158. // Tells whether the request was answered.
  4159. bool get() {
  4160. auto error = Error::Success;
  4161. auto sock = detail::create_client_socket(
  4162. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4163. /*connection_timeout_sec=*/5, 0,
  4164. /*read_timeout_sec=*/5, 0,
  4165. /*write_timeout_sec=*/5, 0, std::string(), error);
  4166. if (sock == INVALID_SOCKET) { return false; }
  4167. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4168. auto ssl = SSL_new(ctx_);
  4169. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4170. SSL_set_fd(ssl, static_cast<int>(sock));
  4171. if (session_) { SSL_set_session(ssl, session_); }
  4172. if (SSL_connect(ssl) != 1) { return false; }
  4173. reused_ = SSL_session_reused(ssl) == 1;
  4174. // Reading the response also takes in a TLS 1.3 session ticket.
  4175. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4176. "Connection: close\r\n\r\n";
  4177. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4178. std::string res;
  4179. char buf[256];
  4180. int n;
  4181. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4182. res.append(buf, static_cast<size_t>(n));
  4183. }
  4184. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4185. SSL_shutdown(ssl);
  4186. return res.find("200 OK") != std::string::npos;
  4187. }
  4188. // Whether the last connection resumed a session
  4189. bool reused() const { return reused_; }
  4190. private:
  4191. SSL_CTX *ctx_;
  4192. SSL_SESSION *session_ = nullptr;
  4193. bool reused_ = false;
  4194. };
  4195. // A client that resumes its session gets through, but not once the client CA
  4196. // has changed, as a resumed session does not show the certificate again.
  4197. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4199. ASSERT_TRUE(svr.is_valid());
  4200. svr.Get("/test", [](const Request &, Response &res) {
  4201. res.set_content("ok", "text/plain");
  4202. });
  4203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. t.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. ResumingClient cli;
  4211. ASSERT_TRUE(cli.get());
  4212. ASSERT_TRUE(cli.get());
  4213. EXPECT_TRUE(cli.reused());
  4214. ASSERT_TRUE(replace_client_ca(svr));
  4215. EXPECT_FALSE(cli.get());
  4216. }
  4217. // A resumed session does not show the certificate again, so the server does
  4218. // not resume one with a verify callback to run on it.
  4219. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4223. return v.preverify_ok;
  4224. });
  4225. svr.Get("/test", [](const Request &, Response &res) {
  4226. res.set_content("ok", "text/plain");
  4227. });
  4228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4229. auto se = detail::scope_exit([&] {
  4230. svr.stop();
  4231. t.join();
  4232. ASSERT_FALSE(svr.is_running());
  4233. });
  4234. svr.wait_until_ready();
  4235. ResumingClient cli;
  4236. ASSERT_TRUE(cli.get());
  4237. ASSERT_TRUE(cli.get());
  4238. EXPECT_FALSE(cli.reused());
  4239. }
  4240. #endif
  4241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4242. // wolfSSL shares its session cache between contexts, so a resumed session
  4243. // could carry a client certificate checked against another server's CA, or
  4244. // against a client CA since replaced.
  4245. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. // Trusts a CA that did not sign the client's certificate.
  4249. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4250. ASSERT_TRUE(other.is_valid());
  4251. for (auto s : {&svr, &other}) {
  4252. s->Get("/test", [](const Request &, Response &res) {
  4253. res.set_content("ok", "text/plain");
  4254. });
  4255. }
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4258. auto se = detail::scope_exit([&] {
  4259. other.stop();
  4260. svr.stop();
  4261. t2.join();
  4262. t.join();
  4263. });
  4264. svr.wait_until_ready();
  4265. other.wait_until_ready();
  4266. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4267. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4268. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4269. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4270. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4271. ASSERT_EQ(WOLFSSL_SUCCESS,
  4272. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4273. WOLFSSL_FILETYPE_PEM));
  4274. WOLFSSL_SESSION *session = nullptr;
  4275. auto session_se = detail::scope_exit([&] {
  4276. if (session) { wolfSSL_SESSION_free(session); }
  4277. });
  4278. // A request over a new connection, resuming `session` when there is one and
  4279. // keeping the connection's own in its place. Tells whether it was answered.
  4280. auto get = [&](int port) {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = wolfSSL_new(ctx);
  4290. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4291. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session) { wolfSSL_set_session(ssl, session); }
  4293. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4294. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4295. "Connection: close\r\n\r\n";
  4296. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4297. std::string res;
  4298. char buf[256];
  4299. int n;
  4300. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4301. res.append(buf, static_cast<size_t>(n));
  4302. }
  4303. wolfSSL_shutdown(ssl);
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. session = wolfSSL_get1_session(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. };
  4308. ASSERT_TRUE(get(PORT));
  4309. EXPECT_FALSE(get(PORT + 1));
  4310. ASSERT_TRUE(get(PORT));
  4311. ASSERT_TRUE(replace_client_ca(svr));
  4312. EXPECT_FALSE(get(PORT));
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4317. ASSERT_TRUE(svr.is_valid());
  4318. svr.Get("/test", [](const Request &, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4322. auto se = detail::scope_exit([&] {
  4323. svr.stop();
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. // A connection that sends no ClientHello keeps its handshake in progress,
  4329. // once the server has had a moment to start it.
  4330. auto error = Error::Success;
  4331. auto sock = detail::create_client_socket(
  4332. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4333. /*connection_timeout_sec=*/5, 0,
  4334. /*read_timeout_sec=*/5, 0,
  4335. /*write_timeout_sec=*/5, 0, std::string(), error);
  4336. ASSERT_NE(INVALID_SOCKET, sock);
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4338. std::string cert_pem, key_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. auto update = std::async(std::launch::async, [&]() {
  4342. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4343. });
  4344. EXPECT_EQ(std::future_status::timeout,
  4345. update.wait_for(std::chrono::milliseconds(200)));
  4346. detail::close_socket(sock);
  4347. EXPECT_TRUE(update.get());
  4348. SSLClient cli(HOST, PORT);
  4349. cli.enable_server_certificate_verification(false);
  4350. auto res = cli.Get("/test");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. #endif
  4355. TEST(ErrorHandlerTest, ContentLength) {
  4356. Server svr;
  4357. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4358. res.status = StatusCode::OK_200;
  4359. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4360. "text/html"); // <= Content-Length still 13
  4361. });
  4362. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!\n", "text/plain");
  4364. res.status = 524;
  4365. });
  4366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. thread.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. {
  4374. Client cli(HOST, PORT);
  4375. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4380. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4381. }
  4382. }
  4383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4384. TEST(ExceptionTest, WithoutExceptionHandler) {
  4385. Server svr;
  4386. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4387. throw std::runtime_error("exception...");
  4388. });
  4389. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4390. throw std::runtime_error("exception\r\n...");
  4391. });
  4392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. listen_thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli("localhost", PORT);
  4400. {
  4401. auto res = cli.Get("/exception");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4411. }
  4412. }
  4413. TEST(ExceptionTest, WithExceptionHandler) {
  4414. Server svr;
  4415. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4416. std::exception_ptr ep) {
  4417. EXPECT_FALSE(ep == nullptr);
  4418. try {
  4419. std::rethrow_exception(ep);
  4420. } catch (std::exception &e) {
  4421. EXPECT_EQ("abc", std::string(e.what()));
  4422. } catch (...) {}
  4423. res.status = StatusCode::InternalServerError_500;
  4424. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4425. "text/html"); // <= Content-Length still 13 at this point
  4426. });
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. throw std::runtime_error("abc");
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. for (size_t i = 0; i < 10; i++) {
  4439. Client cli(HOST, PORT);
  4440. for (size_t j = 0; j < 100; j++) {
  4441. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4445. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4447. }
  4448. cli.set_keep_alive(true);
  4449. for (size_t j = 0; j < 100; j++) {
  4450. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4454. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4456. }
  4457. }
  4458. }
  4459. TEST(ExceptionTest, AndErrorHandler) {
  4460. Server svr;
  4461. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4462. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4463. });
  4464. svr.set_exception_handler(
  4465. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4466. EXPECT_FALSE(ep == nullptr);
  4467. try {
  4468. std::rethrow_exception(ep);
  4469. } catch (std::exception &e) {
  4470. res.set_content(e.what(), "text/html");
  4471. } catch (...) {}
  4472. res.status = StatusCode::InternalServerError_500;
  4473. });
  4474. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("EXCEPTION");
  4476. });
  4477. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4478. res.set_content("ERROR", "text/html");
  4479. res.status = StatusCode::InternalServerError_500;
  4480. });
  4481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4482. auto se = detail::scope_exit([&] {
  4483. svr.stop();
  4484. thread.join();
  4485. ASSERT_FALSE(svr.is_running());
  4486. });
  4487. svr.wait_until_ready();
  4488. Client cli(HOST, PORT);
  4489. {
  4490. auto res = cli.Get("/exception");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("EXCEPTION", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/error");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4499. EXPECT_EQ("ERROR", res->body);
  4500. }
  4501. {
  4502. auto res = cli.Get("/invalid");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4505. EXPECT_EQ("NOT_FOUND", res->body);
  4506. }
  4507. }
  4508. #endif
  4509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4510. // process_request() wraps only routing() in a try/catch, so an exception from
  4511. // any other user callback used to unwind into the task queue - which does not
  4512. // catch - and terminate the process. Each test below runs the server on a
  4513. // single worker thread: a guard that catches the exception but still loses the
  4514. // thread would otherwise be hidden by a spare worker serving the follow-up
  4515. // request. Note that a regression here aborts the whole test binary rather
  4516. // than failing one test.
  4517. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4518. Server svr;
  4519. svr.new_task_queue = [] { return new ThreadPool(1); };
  4520. std::atomic<int> reported{0};
  4521. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4522. if (err == Error::UserCallbackException) { reported++; }
  4523. });
  4524. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4525. res.set_content_provider(
  4526. 1024, "text/plain",
  4527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4528. sink.write("hello", 5);
  4529. throw std::runtime_error("from the content provider");
  4530. });
  4531. });
  4532. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4533. res.set_content("ok", "text/plain");
  4534. });
  4535. auto port = svr.bind_to_any_port(HOST);
  4536. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. listen_thread.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. {
  4544. Client cli(HOST, port);
  4545. cli.set_read_timeout(5, 0);
  4546. EXPECT_FALSE(cli.Get("/throw"));
  4547. }
  4548. EXPECT_TRUE(svr.is_running());
  4549. EXPECT_EQ(1, reported.load());
  4550. // A request on a fresh connection is still served.
  4551. {
  4552. Client cli(HOST, port);
  4553. auto res = cli.Get("/ok");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("ok", res->body);
  4557. }
  4558. }
  4559. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4560. Server svr;
  4561. svr.new_task_queue = [] { return new ThreadPool(1); };
  4562. std::atomic<bool> should_throw{true};
  4563. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4564. res.set_content("hi", "text/plain");
  4565. });
  4566. svr.set_post_routing_handler(
  4567. [&](const Request & /*req*/, Response & /*res*/) {
  4568. if (should_throw) {
  4569. throw std::runtime_error("from the post-routing handler");
  4570. }
  4571. });
  4572. auto port = svr.bind_to_any_port(HOST);
  4573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. listen_thread.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. {
  4581. Client cli(HOST, port);
  4582. cli.set_read_timeout(5, 0);
  4583. EXPECT_FALSE(cli.Get("/hi"));
  4584. }
  4585. EXPECT_TRUE(svr.is_running());
  4586. should_throw = false;
  4587. {
  4588. Client cli(HOST, port);
  4589. auto res = cli.Get("/hi");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("hi", res->body);
  4593. }
  4594. }
  4595. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4596. // The guard reports the caught exception through the error logger, which is
  4597. // a user callback too. A logger that throws has to be contained as well, or
  4598. // the process would terminate from inside the catch.
  4599. Server svr;
  4600. svr.new_task_queue = [] { return new ThreadPool(1); };
  4601. std::atomic<int> reported{0};
  4602. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4603. if (err == Error::UserCallbackException) {
  4604. reported++;
  4605. throw std::runtime_error("from the error logger");
  4606. }
  4607. });
  4608. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4609. res.set_content_provider(
  4610. 1024, "text/plain",
  4611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4612. sink.write("hello", 5);
  4613. throw std::runtime_error("from the content provider");
  4614. });
  4615. });
  4616. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4617. res.set_content("ok", "text/plain");
  4618. });
  4619. auto port = svr.bind_to_any_port(HOST);
  4620. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4621. auto se = detail::scope_exit([&] {
  4622. svr.stop();
  4623. listen_thread.join();
  4624. ASSERT_FALSE(svr.is_running());
  4625. });
  4626. svr.wait_until_ready();
  4627. {
  4628. Client cli(HOST, port);
  4629. cli.set_read_timeout(5, 0);
  4630. EXPECT_FALSE(cli.Get("/throw"));
  4631. }
  4632. EXPECT_TRUE(svr.is_running());
  4633. EXPECT_EQ(1, reported.load());
  4634. {
  4635. Client cli(HOST, port);
  4636. auto res = cli.Get("/ok");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("ok", res->body);
  4640. }
  4641. }
  4642. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4643. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4644. // so the exception unwinds through the ws::WebSocket object on its way to
  4645. // the guard. None of the HTTP cases above cross that.
  4646. Server svr;
  4647. svr.new_task_queue = [] { return new ThreadPool(1); };
  4648. std::atomic<int> reported{0};
  4649. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4650. if (err == Error::UserCallbackException) { reported++; }
  4651. });
  4652. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4653. throw std::runtime_error("from the WebSocket handler");
  4654. });
  4655. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4656. res.set_content("ok", "text/plain");
  4657. });
  4658. auto port = svr.bind_to_any_port(HOST);
  4659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. listen_thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. {
  4667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4668. "/ws");
  4669. auto res = client.connect();
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. // The server dropped the connection instead of dying.
  4672. std::string msg;
  4673. EXPECT_FALSE(client.read(msg));
  4674. client.close();
  4675. }
  4676. EXPECT_TRUE(svr.is_running());
  4677. EXPECT_EQ(1, reported.load());
  4678. {
  4679. Client cli(HOST, port);
  4680. auto res = cli.Get("/ok");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. EXPECT_EQ("ok", res->body);
  4684. }
  4685. }
  4686. #ifdef CPPHTTPLIB_SSL_ENABLED
  4687. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4688. // SSLServer::process_and_close_socket() is a separate overload with its own
  4689. // guard, so it is exercised on its own.
  4690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4691. ASSERT_TRUE(svr.is_valid());
  4692. svr.new_task_queue = [] { return new ThreadPool(1); };
  4693. std::atomic<int> reported{0};
  4694. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4695. if (err == Error::UserCallbackException) { reported++; }
  4696. });
  4697. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4698. res.set_content_provider(
  4699. 1024, "text/plain",
  4700. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4701. sink.write("hello", 5);
  4702. throw std::runtime_error("from the content provider");
  4703. });
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. cli.set_read_timeout(5, 0);
  4720. EXPECT_FALSE(cli.Get("/throw"));
  4721. }
  4722. EXPECT_TRUE(svr.is_running());
  4723. EXPECT_EQ(1, reported.load());
  4724. {
  4725. SSLClient cli(HOST, port);
  4726. cli.enable_server_certificate_verification(false);
  4727. auto res = cli.Get("/ok");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("ok", res->body);
  4731. }
  4732. }
  4733. #endif
  4734. #endif
  4735. TEST(NoContentTest, ContentLength) {
  4736. Server svr;
  4737. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4738. res.status = StatusCode::NoContent_204;
  4739. });
  4740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4741. auto se = detail::scope_exit([&] {
  4742. svr.stop();
  4743. thread.join();
  4744. ASSERT_FALSE(svr.is_running());
  4745. });
  4746. svr.wait_until_ready();
  4747. {
  4748. Client cli(HOST, PORT);
  4749. auto res = cli.Get("/hi");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4752. // RFC 9110 8.6: none in a 204 response
  4753. EXPECT_FALSE(res->has_header("Content-Length"));
  4754. }
  4755. }
  4756. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4757. Server svr;
  4758. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4759. res.set_header("Content-Length", "5");
  4760. res.set_content("hello world", "text/plain");
  4761. });
  4762. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4763. // A body that reads as the last chunk, were it taken as chunked
  4764. res.set_header("Transfer-Encoding", "chunked");
  4765. res.set_content("0\r\n\r\n", "text/plain");
  4766. });
  4767. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "2");
  4769. res.set_content_provider(5, "text/plain",
  4770. [](size_t offset, size_t length, DataSink &sink) {
  4771. sink.write(&"hello"[offset], length);
  4772. return true;
  4773. });
  4774. });
  4775. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4776. res.set_header("Content-Length", "1234");
  4777. });
  4778. thread t = thread([&] { svr.listen(HOST, PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. t.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli(HOST, PORT);
  4786. cli.set_read_timeout(1, 0);
  4787. auto expect_body = [&](const Result &res, const std::string &body) {
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(body, res->body);
  4790. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4791. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4792. };
  4793. Headers identity{{"Accept-Encoding", ""}};
  4794. expect_body(cli.Get("/body", identity), "hello world");
  4795. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4796. expect_body(cli.Get("/body",
  4797. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4798. "he");
  4799. expect_body(cli.Get("/provider", identity), "hello");
  4800. expect_body(cli.Get("/empty", identity), "");
  4801. // A HEAD response may give the length of the body a GET would get.
  4802. auto res = cli.Head("/empty");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4805. }
  4806. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4807. Server svr;
  4808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4809. res.set_content("short", "text/plain");
  4810. });
  4811. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4812. res.body += " with a footer";
  4813. res.set_header("Transfer-Encoding", "chunked");
  4814. });
  4815. thread t = thread([&] { svr.listen(HOST, PORT); });
  4816. auto se = detail::scope_exit([&] {
  4817. svr.stop();
  4818. t.join();
  4819. ASSERT_FALSE(svr.is_running());
  4820. });
  4821. svr.wait_until_ready();
  4822. Client cli(HOST, PORT);
  4823. cli.set_read_timeout(1, 0);
  4824. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("short with a footer", res->body);
  4827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4828. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4829. }
  4830. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4831. Server svr;
  4832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4833. res.set_header("Content-Length", "3");
  4834. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4835. sink.write("abc", 3);
  4836. sink.done();
  4837. return true;
  4838. });
  4839. });
  4840. thread t = thread([&] { svr.listen(HOST, PORT); });
  4841. auto se = detail::scope_exit([&] {
  4842. svr.stop();
  4843. t.join();
  4844. ASSERT_FALSE(svr.is_running());
  4845. });
  4846. svr.wait_until_ready();
  4847. Client cli(HOST, PORT);
  4848. cli.set_keep_alive(true);
  4849. auto res = cli.Get("/");
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ("abc", res->body);
  4852. EXPECT_FALSE(res->has_header("Content-Length"));
  4853. EXPECT_EQ("close", res->get_header_value("Connection"));
  4854. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4855. // No body to delimit
  4856. auto head = cli.Head("/");
  4857. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4858. EXPECT_FALSE(head->has_header("Connection"));
  4859. }
  4860. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4861. #ifdef CPPHTTPLIB_SSL_ENABLED
  4862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4863. ASSERT_TRUE(svr.is_valid());
  4864. #else
  4865. Server svr;
  4866. #endif
  4867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4868. if (req.path == "/routing_handler") {
  4869. res.set_header("PRE_ROUTING", "on");
  4870. res.set_content("Routing Handler", "text/plain");
  4871. return httplib::Server::HandlerResponse::Handled;
  4872. }
  4873. return httplib::Server::HandlerResponse::Unhandled;
  4874. });
  4875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4876. res.set_content("Error", "text/html");
  4877. });
  4878. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4879. if (req.path == "/routing_handler") {
  4880. res.set_header("POST_ROUTING", "on");
  4881. }
  4882. });
  4883. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4884. res.set_content("Hello World!\n", "text/plain");
  4885. });
  4886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4887. auto se = detail::scope_exit([&] {
  4888. svr.stop();
  4889. thread.join();
  4890. ASSERT_FALSE(svr.is_running());
  4891. });
  4892. svr.wait_until_ready();
  4893. {
  4894. #ifdef CPPHTTPLIB_SSL_ENABLED
  4895. SSLClient cli(HOST, PORT);
  4896. cli.enable_server_certificate_verification(false);
  4897. #else
  4898. Client cli(HOST, PORT);
  4899. #endif
  4900. auto res = cli.Get("/routing_handler");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("Routing Handler", res->body);
  4904. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4905. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4906. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4907. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4908. }
  4909. {
  4910. #ifdef CPPHTTPLIB_SSL_ENABLED
  4911. SSLClient cli(HOST, PORT);
  4912. cli.enable_server_certificate_verification(false);
  4913. #else
  4914. Client cli(HOST, PORT);
  4915. #endif
  4916. auto res = cli.Get("/hi");
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("Hello World!\n", res->body);
  4920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4922. }
  4923. {
  4924. #ifdef CPPHTTPLIB_SSL_ENABLED
  4925. SSLClient cli(HOST, PORT);
  4926. cli.enable_server_certificate_verification(false);
  4927. #else
  4928. Client cli(HOST, PORT);
  4929. #endif
  4930. auto res = cli.Get("/aaa");
  4931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4933. EXPECT_EQ("Error", res->body);
  4934. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4935. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4936. }
  4937. }
  4938. TEST(RequestHandlerTest, PreRequestHandler) {
  4939. auto route_path = "/user/:user";
  4940. Server svr;
  4941. svr.Get("/hi", [](const Request &, Response &res) {
  4942. res.set_content("hi", "text/plain");
  4943. });
  4944. svr.Get(route_path, [](const Request &req, Response &res) {
  4945. res.set_content(req.path_params.at("user"), "text/plain");
  4946. });
  4947. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4948. if (req.matched_route == route_path) {
  4949. auto user = req.path_params.at("user");
  4950. if (user != "john") {
  4951. res.status = StatusCode::Forbidden_403;
  4952. res.set_content("error", "text/html");
  4953. return Server::HandlerResponse::Handled;
  4954. }
  4955. }
  4956. return Server::HandlerResponse::Unhandled;
  4957. });
  4958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4959. auto se = detail::scope_exit([&] {
  4960. svr.stop();
  4961. thread.join();
  4962. ASSERT_FALSE(svr.is_running());
  4963. });
  4964. svr.wait_until_ready();
  4965. Client cli(HOST, PORT);
  4966. {
  4967. auto res = cli.Get("/hi");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("hi", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/john");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("john", res->body);
  4977. }
  4978. {
  4979. auto res = cli.Get("/user/invalid-user");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4982. EXPECT_EQ("error", res->body);
  4983. }
  4984. }
  4985. // The pre-request handler must run before the request body is read, so a
  4986. // rejected request never forces the server to buffer a (potentially large)
  4987. // body. Here the posted body is larger than the payload limit: if the body
  4988. // were read first the server would answer 413, but because the pre-request
  4989. // handler runs first it answers 403 and the body is never read.
  4990. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4991. Server svr;
  4992. svr.set_payload_max_length(8);
  4993. auto handler_ran = false;
  4994. svr.Post("/reject", [&](const Request &req, Response &res) {
  4995. handler_ran = true;
  4996. res.set_content(req.body, "text/plain");
  4997. });
  4998. svr.Post("/accept", [](const Request &req, Response &res) {
  4999. res.set_content(req.body, "text/plain");
  5000. });
  5001. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5002. if (req.matched_route == "/reject") {
  5003. res.status = StatusCode::Forbidden_403;
  5004. res.set_content("denied", "text/plain");
  5005. return Server::HandlerResponse::Handled;
  5006. }
  5007. return Server::HandlerResponse::Unhandled;
  5008. });
  5009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5010. auto se = detail::scope_exit([&] {
  5011. svr.stop();
  5012. thread.join();
  5013. ASSERT_FALSE(svr.is_running());
  5014. });
  5015. svr.wait_until_ready();
  5016. Client cli(HOST, PORT);
  5017. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5018. // rejects with 403 before the body is read, so 413 is never reached.
  5019. {
  5020. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5023. EXPECT_EQ("denied", res->body);
  5024. EXPECT_FALSE(handler_ran);
  5025. }
  5026. // An approved route still reads the body and enforces the payload limit.
  5027. {
  5028. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5031. }
  5032. }
  5033. TEST(UserDataTest, BasicOperations) {
  5034. httplib::UserData ud;
  5035. // Initially empty
  5036. EXPECT_FALSE(ud.has("key"));
  5037. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5038. // set and get
  5039. ud.set("key", 42);
  5040. EXPECT_TRUE(ud.has("key"));
  5041. auto *p = ud.get<int>("key");
  5042. ASSERT_NE(nullptr, p);
  5043. EXPECT_EQ(42, *p);
  5044. // Type mismatch → nullptr
  5045. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5046. // Overwrite with different type
  5047. ud.set("key", std::string("hello"));
  5048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5049. auto *s = ud.get<std::string>("key");
  5050. ASSERT_NE(nullptr, s);
  5051. EXPECT_EQ("hello", *s);
  5052. // erase
  5053. ud.erase("key");
  5054. EXPECT_FALSE(ud.has("key"));
  5055. // clear
  5056. ud.set("a", 1);
  5057. ud.set("b", 2);
  5058. ud.clear();
  5059. EXPECT_FALSE(ud.has("a"));
  5060. EXPECT_FALSE(ud.has("b"));
  5061. }
  5062. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5063. struct AuthCtx {
  5064. std::string user_id;
  5065. };
  5066. Server svr;
  5067. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5068. res.user_data.set("auth", AuthCtx{"alice"});
  5069. return Server::HandlerResponse::Unhandled;
  5070. });
  5071. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5072. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5073. ASSERT_NE(nullptr, ctx);
  5074. res.set_content("Hello " + ctx->user_id, "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. Client cli(HOST, PORT);
  5084. auto res = cli.Get("/me");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("Hello alice", res->body);
  5088. }
  5089. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5090. struct RoleCtx {
  5091. std::string role;
  5092. };
  5093. Server svr;
  5094. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5095. res.user_data.set("role", RoleCtx{"admin"});
  5096. return Server::HandlerResponse::Unhandled;
  5097. });
  5098. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5099. auto *ctx = res.user_data.get<RoleCtx>("role");
  5100. ASSERT_NE(nullptr, ctx);
  5101. res.set_content(ctx->role, "text/plain");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/role");
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("admin", res->body);
  5115. }
  5116. TEST(InvalidFormatTest, StatusCode) {
  5117. Server svr;
  5118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5119. res.set_content("Hello World!\n", "text/plain");
  5120. res.status = 9999; // Status should be a three-digit code...
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. auto se = detail::scope_exit([&] {
  5124. svr.stop();
  5125. thread.join();
  5126. ASSERT_FALSE(svr.is_running());
  5127. });
  5128. svr.wait_until_ready();
  5129. {
  5130. Client cli(HOST, PORT);
  5131. auto res = cli.Get("/hi");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. }
  5135. TEST(URLFragmentTest, WithFragment) {
  5136. Server svr;
  5137. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5138. EXPECT_TRUE(req.target == "/hi");
  5139. });
  5140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5141. auto se = detail::scope_exit([&] {
  5142. svr.stop();
  5143. thread.join();
  5144. ASSERT_FALSE(svr.is_running());
  5145. });
  5146. svr.wait_until_ready();
  5147. {
  5148. Client cli(HOST, PORT);
  5149. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5150. EXPECT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. res = cli.Get("/hi%23key1=val1=key2=val2");
  5153. EXPECT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5158. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5159. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5160. Server svr;
  5161. std::vector<std::string> targets;
  5162. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5163. targets.push_back(req.target);
  5164. });
  5165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5166. auto se = detail::scope_exit([&] {
  5167. svr.stop();
  5168. thread.join();
  5169. ASSERT_FALSE(svr.is_running());
  5170. });
  5171. svr.wait_until_ready();
  5172. Client cli(HOST, PORT);
  5173. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5175. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5176. // A '?' after the '#' belongs to the fragment, not to the query.
  5177. Request req;
  5178. req.method = "GET";
  5179. req.path = "/hi#f?x=1";
  5180. req.params.emplace("a", "1");
  5181. Response res;
  5182. auto error = Error::Success;
  5183. EXPECT_TRUE(cli.send(req, res, error));
  5184. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5185. "/hi?a=1"}),
  5186. targets);
  5187. }
  5188. TEST(HeaderWriter, SetHeaderWriter) {
  5189. Server svr;
  5190. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5191. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5192. return detail::write_headers(strm, hdrs);
  5193. });
  5194. svr.Get("/hi", [](const Request &req, Response &res) {
  5195. auto it = req.headers.find("CustomClientHeader");
  5196. EXPECT_TRUE(it != req.headers.end());
  5197. EXPECT_EQ(it->second, "CustomClientValue");
  5198. res.set_content("Hello World!\n", "text/plain");
  5199. });
  5200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5201. auto se = detail::scope_exit([&] {
  5202. svr.stop();
  5203. thread.join();
  5204. ASSERT_FALSE(svr.is_running());
  5205. });
  5206. svr.wait_until_ready();
  5207. {
  5208. Client cli(HOST, PORT);
  5209. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5210. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5211. return detail::write_headers(strm, hdrs);
  5212. });
  5213. auto res = cli.Get("/hi");
  5214. EXPECT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. auto it = res->headers.find("CustomServerHeader");
  5217. EXPECT_TRUE(it != res->headers.end());
  5218. EXPECT_EQ(it->second, "CustomServerValue");
  5219. }
  5220. }
  5221. class ServerTest : public ::testing::Test {
  5222. protected:
  5223. ServerTest()
  5224. : cli_(HOST, PORT)
  5225. #ifdef CPPHTTPLIB_SSL_ENABLED
  5226. ,
  5227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5228. #endif
  5229. {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. cli_.enable_server_certificate_verification(false);
  5232. #endif
  5233. // Allow LARGE_DATA (100MB) responses
  5234. cli_.set_payload_max_length(200 * 1024 * 1024);
  5235. }
  5236. virtual void SetUp() {
  5237. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5238. svr_.set_payload_max_length(200 * 1024 * 1024);
  5239. svr_.set_mount_point("/", "./www");
  5240. svr_.set_mount_point("/mount", "./www2");
  5241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5242. svr_.Get("/hi",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_content("Hello World!", "text/plain");
  5245. })
  5246. .Get("/file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/test.html");
  5249. })
  5250. .Get("/file_content_with_content_type",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_file_content("./www/file", "text/plain");
  5253. })
  5254. .Get("/invalid_file_content",
  5255. [&](const Request & /*req*/, Response &res) {
  5256. res.set_file_content("./www/dir/invalid_file_path");
  5257. })
  5258. .Get("/http_response_splitting",
  5259. [&](const Request & /*req*/, Response &res) {
  5260. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a", "1\nSet-Cookie: a=1");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a", "1\rSet-Cookie: a=1");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\r\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_header("a\rb", "0");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("a"));
  5275. res.set_header("a\nb", "0");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_redirect("1\r\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("Location"));
  5281. })
  5282. .Get("/slow",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(4));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #if 0
  5288. .Post("/slowpost",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. std::this_thread::sleep_for(std::chrono::seconds(2));
  5291. res.set_content("slow", "text/plain");
  5292. })
  5293. #endif
  5294. .Get("/remote_addr",
  5295. [&](const Request &req, Response &res) {
  5296. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5297. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5301. #endif
  5302. res.set_content(req.remote_addr, "text/plain");
  5303. })
  5304. .Get("/local_addr",
  5305. [&](const Request &req, Response &res) {
  5306. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5307. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5311. #endif
  5312. auto local_addr = req.local_addr;
  5313. auto local_port = std::to_string(req.local_port);
  5314. res.set_content(local_addr.append(":").append(local_port),
  5315. "text/plain");
  5316. })
  5317. .Get("/endwith%",
  5318. [&](const Request & /*req*/, Response &res) {
  5319. res.set_content("Hello World!", "text/plain");
  5320. })
  5321. .Get("/a\\+\\+b",
  5322. [&](const Request &req, Response &res) {
  5323. ASSERT_TRUE(req.has_param("a +b"));
  5324. auto val = req.get_param_value("a +b");
  5325. res.set_content(val, "text/plain");
  5326. })
  5327. .Get("/", [&](const Request & /*req*/,
  5328. Response &res) { res.set_redirect("/hi"); })
  5329. .Post("/1",
  5330. [](const Request & /*req*/, Response &res) {
  5331. res.set_redirect("/2", StatusCode::SeeOther_303);
  5332. })
  5333. .Get("/2",
  5334. [](const Request & /*req*/, Response &res) {
  5335. res.set_content("redirected.", "text/plain");
  5336. res.status = StatusCode::OK_200;
  5337. })
  5338. .Post("/person",
  5339. [&](const Request &req, Response &res) {
  5340. if (req.has_param("name") && req.has_param("note")) {
  5341. persons_[req.get_param_value("name")] =
  5342. req.get_param_value("note");
  5343. } else {
  5344. res.status = StatusCode::BadRequest_400;
  5345. }
  5346. })
  5347. .Put("/person",
  5348. [&](const Request &req, Response &res) {
  5349. if (req.has_param("name") && req.has_param("note")) {
  5350. persons_[req.get_param_value("name")] =
  5351. req.get_param_value("note");
  5352. } else {
  5353. res.status = StatusCode::BadRequest_400;
  5354. }
  5355. })
  5356. .Get("/person/(.*)",
  5357. [&](const Request &req, Response &res) {
  5358. string name = req.matches[1];
  5359. if (persons_.find(name) != persons_.end()) {
  5360. auto note = persons_[name];
  5361. res.set_content(note, "text/plain");
  5362. } else {
  5363. res.status = StatusCode::NotFound_404;
  5364. }
  5365. })
  5366. .Delete("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name")) {
  5369. string name = req.get_param_value("name");
  5370. if (persons_.find(name) != persons_.end()) {
  5371. persons_.erase(name);
  5372. res.set_content("DELETED", "text/plain");
  5373. } else {
  5374. res.status = StatusCode::NotFound_404;
  5375. }
  5376. } else {
  5377. res.status = StatusCode::BadRequest_400;
  5378. }
  5379. })
  5380. .Post("/x-www-form-urlencoded-json",
  5381. [&](const Request &req, Response &res) {
  5382. auto json = req.get_param_value("json");
  5383. ASSERT_EQ(JSON_DATA, json);
  5384. res.set_content(json, "appliation/json");
  5385. res.status = StatusCode::OK_200;
  5386. })
  5387. .Get("/streamed-chunked",
  5388. [&](const Request & /*req*/, Response &res) {
  5389. res.set_chunked_content_provider(
  5390. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5391. sink.os << "123";
  5392. sink.os << "456";
  5393. sink.os << "789";
  5394. sink.done();
  5395. return true;
  5396. });
  5397. })
  5398. .Get("/streamed-chunked-with-prohibited-trailer",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. auto i = new int(0);
  5401. // Declare both a prohibited trailer (Content-Length) and an
  5402. // allowed one
  5403. res.set_header("Trailer", "Content-Length, X-Allowed");
  5404. res.set_chunked_content_provider(
  5405. "text/plain",
  5406. [i](size_t /*offset*/, DataSink &sink) {
  5407. switch (*i) {
  5408. case 0: sink.os << "123"; break;
  5409. case 1: sink.os << "456"; break;
  5410. case 2: sink.os << "789"; break;
  5411. case 3: {
  5412. sink.done_with_trailer(
  5413. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5414. } break;
  5415. }
  5416. (*i)++;
  5417. return true;
  5418. },
  5419. [i](bool success) {
  5420. EXPECT_TRUE(success);
  5421. delete i;
  5422. });
  5423. })
  5424. .Get("/streamed-chunked2",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. auto i = new int(0);
  5427. res.set_chunked_content_provider(
  5428. "text/plain",
  5429. [i](size_t /*offset*/, DataSink &sink) {
  5430. switch (*i) {
  5431. case 0: sink.os << "123"; break;
  5432. case 1: sink.os << "456"; break;
  5433. case 2: sink.os << "789"; break;
  5434. case 3: sink.done(); break;
  5435. }
  5436. (*i)++;
  5437. return true;
  5438. },
  5439. [i](bool success) {
  5440. EXPECT_TRUE(success);
  5441. delete i;
  5442. });
  5443. })
  5444. .Get("/streamed-chunked-with-trailer",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. auto i = new int(0);
  5447. res.set_header("Trailer", "Dummy1, Dummy2");
  5448. res.set_chunked_content_provider(
  5449. "text/plain",
  5450. [i](size_t /*offset*/, DataSink &sink) {
  5451. switch (*i) {
  5452. case 0: sink.os << "123"; break;
  5453. case 1: sink.os << "456"; break;
  5454. case 2: sink.os << "789"; break;
  5455. case 3: {
  5456. sink.done_with_trailer(
  5457. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5458. } break;
  5459. }
  5460. (*i)++;
  5461. return true;
  5462. },
  5463. [i](bool success) {
  5464. EXPECT_TRUE(success);
  5465. delete i;
  5466. });
  5467. })
  5468. .Get("/streamed",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content_provider(
  5471. 6, "text/plain",
  5472. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5473. sink.os << (offset < 3 ? "a" : "b");
  5474. return true;
  5475. });
  5476. })
  5477. .Get("/streamed-without-length",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. auto data = new std::string("abcdefg");
  5480. res.set_content_provider(
  5481. "text/plain",
  5482. [data](size_t offset, DataSink &sink) {
  5483. if (offset < data->size()) {
  5484. sink.os << data->substr(offset);
  5485. }
  5486. sink.done();
  5487. return true;
  5488. },
  5489. [data](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete data;
  5492. });
  5493. })
  5494. .Get("/streamed-with-range",
  5495. [&](const Request &req, Response &res) {
  5496. auto data = new std::string("abcdefg");
  5497. // An explicit status keeps the server from picking the 206 it
  5498. // would otherwise choose for a ranged request, so the response
  5499. // is not a partial representation.
  5500. auto status = req.get_param_value("status");
  5501. if (status == "200") {
  5502. res.status = StatusCode::OK_200;
  5503. } else if (status == "403") {
  5504. res.status = StatusCode::Forbidden_403;
  5505. }
  5506. res.set_content_provider(
  5507. data->size(), "text/plain",
  5508. [data](size_t offset, size_t length, DataSink &sink) {
  5509. size_t DATA_CHUNK_SIZE = 4;
  5510. const auto &d = *data;
  5511. auto out_len =
  5512. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5513. auto ret =
  5514. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5515. EXPECT_TRUE(ret);
  5516. return true;
  5517. },
  5518. [data, &req](bool success) {
  5519. EXPECT_EQ(success, !req.has_param("error"));
  5520. delete data;
  5521. });
  5522. })
  5523. .Get("/streamed-cancel",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content_provider(
  5526. size_t(-1), "text/plain",
  5527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5528. sink.os << "data_chunk";
  5529. return true;
  5530. });
  5531. })
  5532. .Get("/regex-with-delimiter",
  5533. [&](const Request &req, Response & /*res*/) {
  5534. ASSERT_TRUE(req.has_param("key"));
  5535. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5536. })
  5537. .Get("/with-range",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content("abcdefg", "text/plain");
  5540. })
  5541. .Get("/test-start-time",
  5542. [&](const Request &req, Response & /*res*/) {
  5543. EXPECT_NE(req.start_time_,
  5544. std::chrono::steady_clock::time_point::min());
  5545. })
  5546. .Get("/with-range-customized-response",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. res.status = StatusCode::BadRequest_400;
  5549. res.set_content(JSON_DATA, "application/json");
  5550. })
  5551. .Post("/chunked",
  5552. [&](const Request &req, Response & /*res*/) {
  5553. EXPECT_EQ(req.body, "dechunked post body");
  5554. })
  5555. .Post("/large-chunked",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. std::string expected(6 * 30 * 1024u, 'a');
  5558. EXPECT_EQ(req.body, expected);
  5559. })
  5560. .Post("/multipart",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5563. req.form.get_field_count("text2") +
  5564. req.form.get_field_count("file3") +
  5565. req.form.get_field_count("file4"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5567. req.form.get_file_count("file2"));
  5568. ASSERT_TRUE(!req.form.has_file("???"));
  5569. ASSERT_TRUE(!req.form.has_field("???"));
  5570. ASSERT_TRUE(req.body.empty());
  5571. {
  5572. const auto &text = req.form.get_field("text1");
  5573. EXPECT_EQ("text default", text);
  5574. }
  5575. {
  5576. const auto &text = req.form.get_field("text2");
  5577. EXPECT_EQ("aωb", text);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file1");
  5581. EXPECT_EQ("hello.txt", file.filename);
  5582. EXPECT_EQ("text/plain", file.content_type);
  5583. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5584. }
  5585. {
  5586. const auto &file = req.form.get_file("file2");
  5587. EXPECT_EQ("world.json", file.filename);
  5588. EXPECT_EQ("application/json", file.content_type);
  5589. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5590. }
  5591. {
  5592. const auto &text = req.form.get_field("file3");
  5593. EXPECT_EQ(0u, text.size());
  5594. }
  5595. {
  5596. const auto &text = req.form.get_field("file4");
  5597. EXPECT_EQ(0u, text.size());
  5598. }
  5599. })
  5600. .Post("/multipart/multi_file_values",
  5601. [&](const Request &req, Response & /*res*/) {
  5602. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5603. req.form.get_field_count("multi_text1"));
  5604. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5605. ASSERT_TRUE(!req.form.has_file("???"));
  5606. ASSERT_TRUE(!req.form.has_field("???"));
  5607. ASSERT_TRUE(req.body.empty());
  5608. {
  5609. const auto &text = req.form.get_field("text");
  5610. EXPECT_EQ("default text", text);
  5611. }
  5612. {
  5613. const auto &text1_values = req.form.get_fields("multi_text1");
  5614. EXPECT_EQ(2u, text1_values.size());
  5615. EXPECT_EQ("aaaaa", text1_values[0]);
  5616. EXPECT_EQ("bbbbb", text1_values[1]);
  5617. }
  5618. {
  5619. const auto &file1_values = req.form.get_files("multi_file1");
  5620. EXPECT_EQ(2u, file1_values.size());
  5621. auto file1 = file1_values[0];
  5622. EXPECT_EQ(file1.filename, "hello.txt");
  5623. EXPECT_EQ(file1.content_type, "text/plain");
  5624. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5625. auto file2 = file1_values[1];
  5626. EXPECT_EQ(file2.filename, "world.json");
  5627. EXPECT_EQ(file2.content_type, "application/json");
  5628. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5629. }
  5630. })
  5631. .Post("/empty",
  5632. [&](const Request &req, Response &res) {
  5633. EXPECT_EQ(req.body, "");
  5634. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5636. res.set_content("empty", "text/plain");
  5637. })
  5638. .Post("/empty-no-content-type",
  5639. [&](const Request &req, Response &res) {
  5640. EXPECT_EQ(req.body, "");
  5641. EXPECT_FALSE(req.has_header("Content-Type"));
  5642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5643. res.set_content("empty-no-content-type", "text/plain");
  5644. })
  5645. .Post("/path-only",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(req.body, "");
  5648. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5649. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5650. res.set_content("path-only", "text/plain");
  5651. })
  5652. .Post("/path-headers-only",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(req.body, "");
  5655. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5657. EXPECT_EQ("world", req.get_header_value("hello"));
  5658. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5659. res.set_content("path-headers-only", "text/plain");
  5660. })
  5661. .Post("/post-large",
  5662. [&](const Request &req, Response &res) {
  5663. EXPECT_EQ(req.body, LARGE_DATA);
  5664. res.set_content(req.body, "text/plain");
  5665. })
  5666. .Post("/post-loopback",
  5667. [&](const Request &, Response &res,
  5668. ContentReader const &content_reader) {
  5669. std::string body;
  5670. content_reader([&](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. res.set_content(body, "text/plain");
  5675. })
  5676. .Put("/put-loopback",
  5677. [&](const Request &, Response &res,
  5678. ContentReader const &content_reader) {
  5679. std::string body;
  5680. content_reader([&](const char *data, size_t data_length) {
  5681. body.append(data, data_length);
  5682. return true;
  5683. });
  5684. res.set_content(body, "text/plain");
  5685. })
  5686. .Patch("/patch-loopback",
  5687. [&](const Request &, Response &res,
  5688. ContentReader const &content_reader) {
  5689. std::string body;
  5690. content_reader([&](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. res.set_content(body, "text/plain");
  5695. })
  5696. .Put("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Put("/put",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "PUT");
  5706. res.set_content(req.body, "text/plain");
  5707. })
  5708. .Put("/put-large",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, LARGE_DATA);
  5711. res.set_content(req.body, "text/plain");
  5712. })
  5713. .Patch("/patch",
  5714. [&](const Request &req, Response &res) {
  5715. EXPECT_EQ(req.body, "PATCH");
  5716. res.set_content(req.body, "text/plain");
  5717. })
  5718. .Delete("/delete",
  5719. [&](const Request & /*req*/, Response &res) {
  5720. res.set_content("DELETE", "text/plain");
  5721. })
  5722. .Delete("/delete-body",
  5723. [&](const Request &req, Response &res) {
  5724. EXPECT_EQ(req.body, "content");
  5725. res.set_content(req.body, "text/plain");
  5726. })
  5727. .Options(R"(\*)",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5730. })
  5731. .CustomRoute("PROPFIND", "/dav/:id",
  5732. [&](const Request &req, Response &res) {
  5733. res.set_header("x-body-size",
  5734. std::to_string(req.body.size()));
  5735. res.set_header("x-matched-route", req.matched_route);
  5736. res.set_header("x-dav-id", req.path_params.at("id"));
  5737. res.status = StatusCode::MultiStatus_207;
  5738. res.set_content(req.body, "application/xml");
  5739. })
  5740. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5741. [&](const Request &req, Response &res) {
  5742. res.set_header("x-dav-match", req.matches[1]);
  5743. res.status = StatusCode::MultiStatus_207;
  5744. })
  5745. .CustomRoute("MKCOL", "/dav-mkcol",
  5746. [&](const Request &req, Response &res) {
  5747. EXPECT_TRUE(req.body.empty());
  5748. res.status = StatusCode::Created_201;
  5749. })
  5750. .CustomRoute(
  5751. "REPORT", "/dav-report",
  5752. [&](const Request & /*req*/, Response &res,
  5753. const ContentReader &content_reader) {
  5754. std::string body;
  5755. content_reader([&](const char *data, size_t data_length) {
  5756. body.append(data, data_length);
  5757. return true;
  5758. });
  5759. res.set_header("x-body-size", std::to_string(body.size()));
  5760. res.status = StatusCode::MultiStatus_207;
  5761. res.set_content(body, "application/xml");
  5762. })
  5763. .Get("/request-target",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5766. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5767. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5768. })
  5769. .Get("/long-query-value",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5772. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5773. })
  5774. .Get("/too-long-query-value",
  5775. [&](const Request &req, Response & /*res*/) {
  5776. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5777. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5778. })
  5779. .Get("/array-param",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5782. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5783. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5784. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5785. })
  5786. .Get("/array-param-values",
  5787. [&](const Request &req, Response & /*res*/) {
  5788. auto values = req.get_param_values("array");
  5789. EXPECT_EQ(3u, values.size());
  5790. EXPECT_EQ("value1", values[0]);
  5791. EXPECT_EQ("value2", values[1]);
  5792. EXPECT_EQ("value3", values[2]);
  5793. auto empty = req.get_param_values("nonexistent");
  5794. EXPECT_TRUE(empty.empty());
  5795. })
  5796. .Post("/validate-no-multiple-headers",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5799. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5800. })
  5801. .Post("/content_receiver",
  5802. [&](const Request &req, Response &res,
  5803. const ContentReader &content_reader) {
  5804. if (req.is_multipart_form_data()) {
  5805. std::vector<FormData> items;
  5806. content_reader(
  5807. [&](const FormData &file) {
  5808. items.push_back(file);
  5809. return true;
  5810. },
  5811. [&](const char *data, size_t data_length) {
  5812. items.back().content.append(data, data_length);
  5813. return true;
  5814. });
  5815. EXPECT_EQ(5u, items.size());
  5816. {
  5817. const auto &file = get_file_value(items, "text1");
  5818. EXPECT_TRUE(file.filename.empty());
  5819. EXPECT_EQ("text default", file.content);
  5820. }
  5821. {
  5822. const auto &file = get_file_value(items, "text2");
  5823. EXPECT_TRUE(file.filename.empty());
  5824. EXPECT_EQ("aωb", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file1");
  5828. EXPECT_EQ("hello.txt", file.filename);
  5829. EXPECT_EQ("text/plain", file.content_type);
  5830. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file2");
  5834. EXPECT_EQ("world.json", file.filename);
  5835. EXPECT_EQ("application/json", file.content_type);
  5836. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5837. }
  5838. {
  5839. const auto &file = get_file_value(items, "file3");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("application/octet-stream", file.content_type);
  5842. EXPECT_EQ(0u, file.content.size());
  5843. }
  5844. } else {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. EXPECT_EQ(7U, data_length);
  5848. body.append(data, data_length);
  5849. return true;
  5850. });
  5851. EXPECT_EQ(body, "content");
  5852. res.set_content(body, "text/plain");
  5853. }
  5854. })
  5855. .Put("/content_receiver",
  5856. [&](const Request & /*req*/, Response &res,
  5857. const ContentReader &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. EXPECT_EQ(body, "content");
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Patch("/content_receiver",
  5867. [&](const Request & /*req*/, Response &res,
  5868. const ContentReader &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_EQ(body, "content");
  5875. res.set_content(body, "text/plain");
  5876. })
  5877. .Post("/query-string-and-body",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. ASSERT_TRUE(req.has_param("key"));
  5880. EXPECT_EQ(req.get_param_value("key"), "value");
  5881. EXPECT_EQ(req.body, "content");
  5882. })
  5883. .Get("/last-request",
  5884. [&](const Request &req, Response & /*res*/) {
  5885. EXPECT_EQ("close", req.get_header_value("Connection"));
  5886. })
  5887. .Get(R"(/redirect/(\d+))",
  5888. [&](const Request &req, Response &res) {
  5889. auto num = std::stoi(req.matches[1]) + 1;
  5890. std::string url = "/redirect/" + std::to_string(num);
  5891. res.set_redirect(url);
  5892. })
  5893. .Post("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Put("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Patch("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Delete("/binary",
  5918. [&](const Request &req, Response &res) {
  5919. EXPECT_EQ(4U, req.body.size());
  5920. EXPECT_EQ("application/octet-stream",
  5921. req.get_header_value("Content-Type"));
  5922. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5923. res.set_content(req.body, "application/octet-stream");
  5924. })
  5925. .Get("/issue1772",
  5926. [&](const Request & /*req*/, Response &res) {
  5927. res.status = 401;
  5928. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5929. })
  5930. .Delete("/issue609",
  5931. [](const httplib::Request &, httplib::Response &res,
  5932. const httplib::ContentReader &) {
  5933. res.set_content("ok", "text/plain");
  5934. })
  5935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5936. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5937. .Get("/compress",
  5938. [&](const Request & /*req*/, Response &res) {
  5939. res.set_content(
  5940. "12345678901234567890123456789012345678901234567890123456789"
  5941. "01234567890123456789012345678901234567890",
  5942. "text/plain");
  5943. })
  5944. .Get("/compress-with-charset",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content(
  5947. "12345678901234567890123456789012345678901234567890123456789"
  5948. "01234567890123456789012345678901234567890",
  5949. "application/json; charset=utf-8");
  5950. })
  5951. .Get("/nocompress",
  5952. [&](const Request & /*req*/, Response &res) {
  5953. res.set_content(
  5954. "12345678901234567890123456789012345678901234567890123456789"
  5955. "01234567890123456789012345678901234567890",
  5956. "application/octet-stream");
  5957. })
  5958. .Post("/compress-multipart",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(2u, req.form.fields.size());
  5961. ASSERT_TRUE(!req.form.has_field("???"));
  5962. {
  5963. const auto &text = req.form.get_field("key1");
  5964. EXPECT_EQ("test", text);
  5965. }
  5966. {
  5967. const auto &text = req.form.get_field("key2");
  5968. EXPECT_EQ("--abcdefg123", text);
  5969. }
  5970. })
  5971. #endif
  5972. ;
  5973. persons_["john"] = "programmer";
  5974. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5975. svr_.wait_until_ready();
  5976. }
  5977. virtual void TearDown() {
  5978. svr_.stop();
  5979. if (!request_threads_.empty()) {
  5980. std::this_thread::sleep_for(std::chrono::seconds(1));
  5981. for (auto &t : request_threads_) {
  5982. t.join();
  5983. }
  5984. }
  5985. t_.join();
  5986. }
  5987. map<string, string> persons_;
  5988. #ifdef CPPHTTPLIB_SSL_ENABLED
  5989. SSLClient cli_;
  5990. SSLServer svr_;
  5991. #else
  5992. Client cli_;
  5993. Server svr_;
  5994. #endif
  5995. thread t_;
  5996. std::vector<thread> request_threads_;
  5997. };
  5998. TEST_F(ServerTest, GetMethod200) {
  5999. auto res = cli_.Get("/hi");
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ("HTTP/1.1", res->version);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("OK", res->reason);
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6006. EXPECT_EQ("Hello World!", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetEmptyFile) {
  6009. auto res = cli_.Get("/empty_file");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContent) {
  6017. auto res = cli_.Get("/file_content");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6022. EXPECT_EQ("test.html", res->body);
  6023. }
  6024. TEST_F(ServerTest, GetFileContentWithRange) {
  6025. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6030. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("est", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetFileContentWithContentType) {
  6034. auto res = cli_.Get("/file_content_with_content_type");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6038. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6039. EXPECT_EQ("file\n", res->body);
  6040. }
  6041. TEST_F(ServerTest, GetInvalidFileContent) {
  6042. auto res = cli_.Get("/invalid_file_content");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6045. }
  6046. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6047. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ("HTTP/1.1", res->version);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetMethod302) {
  6056. auto res = cli_.Get("/");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::Found_302, res->status);
  6059. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6060. }
  6061. TEST_F(ServerTest, GetMethod302Redirect) {
  6062. cli_.set_follow_location(true);
  6063. auto res = cli_.Get("/");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("Hello World!", res->body);
  6067. EXPECT_EQ("/hi", res->location);
  6068. }
  6069. TEST_F(ServerTest, GetMethod404) {
  6070. auto res = cli_.Get("/invalid");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, HeadMethod200) {
  6075. auto res = cli_.Head("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod200Static) {
  6082. auto res = cli_.Head("/mount/dir/index.html");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6086. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, HeadMethod404) {
  6090. auto res = cli_.Head("/invalid");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6093. EXPECT_TRUE(res->body.empty());
  6094. }
  6095. TEST_F(ServerTest, GetMethodPersonJohn) {
  6096. auto res = cli_.Get("/person/john");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::OK_200, res->status);
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("programmer", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostMethod1) {
  6103. auto res = cli_.Get("/person/john1");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6106. res = cli_.Post("/person", "name=john1&note=coder",
  6107. "application/x-www-form-urlencoded");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john1");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("coder", res->body);
  6115. }
  6116. TEST_F(ServerTest, PostMethod2) {
  6117. auto res = cli_.Get("/person/john2");
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6120. Params params;
  6121. params.emplace("name", "john2");
  6122. params.emplace("note", "coder");
  6123. res = cli_.Post("/person", params);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::OK_200, res->status);
  6126. res = cli_.Get("/person/john2");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. ASSERT_EQ("coder", res->body);
  6131. }
  6132. TEST_F(ServerTest, PutMethod3) {
  6133. auto res = cli_.Get("/person/john3");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6136. Params params;
  6137. params.emplace("name", "john3");
  6138. params.emplace("note", "coder");
  6139. res = cli_.Put("/person", params);
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. res = cli_.Get("/person/john3");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. ASSERT_EQ("coder", res->body);
  6147. }
  6148. TEST_F(ServerTest, DeleteMethod1) {
  6149. auto res = cli_.Get("/person/john4");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6152. Params params;
  6153. params.emplace("name", "john4");
  6154. params.emplace("note", "coder");
  6155. res = cli_.Post("/person", params);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::OK_200, res->status);
  6158. res = cli_.Get("/person/john4");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::OK_200, res->status);
  6161. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6162. ASSERT_EQ("coder", res->body);
  6163. Params delete_params;
  6164. delete_params.emplace("name", "john4");
  6165. res = cli_.Delete("/person", delete_params);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. ASSERT_EQ("DELETED", res->body);
  6169. res = cli_.Get("/person/john4");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, DeleteMethod2) {
  6174. auto res = cli_.Get("/person/john5");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6177. Params params;
  6178. params.emplace("name", "john5");
  6179. params.emplace("note", "developer");
  6180. res = cli_.Post("/person", params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli_.Get("/person/john5");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. ASSERT_EQ("developer", res->body);
  6188. Params delete_params;
  6189. delete_params.emplace("name", "john5");
  6190. Headers headers;
  6191. headers.emplace("Custom-Header", "test-value");
  6192. res = cli_.Delete("/person", headers, delete_params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("DELETED", res->body);
  6196. res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. }
  6200. TEST_F(ServerTest, DeleteMethod3) {
  6201. auto res = cli_.Get("/person/john6");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6204. Params params;
  6205. params.emplace("name", "john6");
  6206. params.emplace("note", "tester");
  6207. res = cli_.Post("/person", params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. res = cli_.Get("/person/john6");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6214. ASSERT_EQ("tester", res->body);
  6215. Params delete_params;
  6216. delete_params.emplace("name", "john6");
  6217. Headers headers;
  6218. headers.emplace("Custom-Header", "test-value");
  6219. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("DELETED", res->body);
  6223. res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. }
  6227. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6228. Params params;
  6229. params.emplace("json", JSON_DATA);
  6230. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ(JSON_DATA, res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContent) {
  6236. auto res = cli_.Post("/empty", "", "text/plain");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6242. auto res = cli_.Post("/empty-no-content-type");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("empty-no-content-type", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathOnly) {
  6248. auto res = cli_.Post("/path-only");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("path-only", res->body);
  6252. }
  6253. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6254. auto res = cli_.Post("/path-headers-only",
  6255. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. ASSERT_EQ("path-headers-only", res->body);
  6259. }
  6260. TEST_F(ServerTest, PostLarge) {
  6261. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ(LARGE_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6267. auto res = cli_.Put("/empty-no-content-type");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. ASSERT_EQ("empty-no-content-type", res->body);
  6271. }
  6272. TEST_F(ServerTest, GetMethodDir) {
  6273. auto res = cli_.Get("/dir/");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6277. auto body = R"(<html>
  6278. <head>
  6279. </head>
  6280. <body>
  6281. <a href="/dir/test.html">Test</a>
  6282. <a href="/hi">hi</a>
  6283. </body>
  6284. </html>
  6285. )";
  6286. EXPECT_EQ(body, res->body);
  6287. }
  6288. TEST_F(ServerTest, GetMethodDirTest) {
  6289. auto res = cli_.Get("/dir/test.html");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6293. EXPECT_EQ("test.html", res->body);
  6294. }
  6295. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6296. auto res = cli_.Get("/dir/../dir/test.html");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6299. }
  6300. TEST_F(ServerTest, GetMethodInvalidPath) {
  6301. auto res = cli_.Get("/dir/../test.html");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. }
  6305. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6306. auto res = cli_.Get("/../www/dir/test.html");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6309. }
  6310. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6311. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6314. }
  6315. TEST_F(ServerTest, GetMethodDirMountTest) {
  6316. auto res = cli_.Get("/mount/dir/test.html");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6320. EXPECT_EQ("test.html", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6323. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6328. auto res = cli_.Get("/mount/dir/../test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6333. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6338. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6341. }
  6342. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6343. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6348. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6353. auto res = cli_.Get("/mount/dir");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6357. }
  6358. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6359. auto res = cli_.Get("//dir");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. EXPECT_FALSE(res->has_header("Location"));
  6363. }
  6364. TEST_F(ServerTest, PostMethod303) {
  6365. auto res = cli_.Post("/1", "body", "text/plain");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6368. EXPECT_EQ("/2", res->get_header_value("Location"));
  6369. }
  6370. TEST_F(ServerTest, PostMethod303Redirect) {
  6371. cli_.set_follow_location(true);
  6372. auto res = cli_.Post("/1", "body", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("redirected.", res->body);
  6376. EXPECT_EQ("/2", res->location);
  6377. }
  6378. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6379. auto res = cli_.Get("/dir/test.abcde");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6383. EXPECT_EQ("abcde", res->body);
  6384. }
  6385. TEST_F(ServerTest, StaticFileRange) {
  6386. auto res =
  6387. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ(true, res->has_header("Content-Range"));
  6393. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6394. EXPECT_EQ(std::string("cd"), res->body);
  6395. }
  6396. TEST_F(ServerTest, StaticFileRanges) {
  6397. auto res = cli_.Get("/dir/test.abcde",
  6398. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6401. EXPECT_TRUE(
  6402. res->get_header_value("Content-Type")
  6403. .find(
  6404. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6405. 0);
  6406. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6407. }
  6408. TEST_F(ServerTest, StaticFileRangeHead) {
  6409. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. }
  6417. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6418. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6425. res->get_header_value("Content-Range"));
  6426. EXPECT_EQ("LAST\n", res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6429. auto res =
  6430. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6434. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6437. }
  6438. TEST_F(ServerTest, StaticFileBigFile) {
  6439. auto res = cli_.Get("/dir/1MB.txt");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6444. }
  6445. TEST_F(ServerTest, InvalidBaseDirMount) {
  6446. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6447. }
  6448. TEST_F(ServerTest, Binary) {
  6449. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6450. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6451. "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. res = cli_.Put("/binary", binary.data(), binary.size(),
  6456. "application/octet-stream");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ(4U, res->body.size());
  6460. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6461. "application/octet-stream");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. ASSERT_EQ(StatusCode::OK_200, res->status);
  6464. ASSERT_EQ(4U, res->body.size());
  6465. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6466. "application/octet-stream");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::OK_200, res->status);
  6469. ASSERT_EQ(4U, res->body.size());
  6470. }
  6471. TEST_F(ServerTest, BinaryString) {
  6472. auto binary = std::string("\x00\x01\x02\x03", 4);
  6473. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, EmptyRequest) {
  6491. auto res = cli_.Get("");
  6492. ASSERT_TRUE(!res);
  6493. EXPECT_EQ(Error::Connection, res.error());
  6494. }
  6495. TEST_F(ServerTest, LongRequest) {
  6496. std::string request;
  6497. for (size_t i = 0; i < 545; i++) {
  6498. request += "/TooLongRequest";
  6499. }
  6500. request += "OK";
  6501. auto res = cli_.Get(request.c_str());
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, TooLongRequest) {
  6506. std::string request;
  6507. for (size_t i = 0; i < 546; i++) {
  6508. request += "/TooLongRequest";
  6509. }
  6510. request += "_NG";
  6511. auto start = std::chrono::high_resolution_clock::now();
  6512. cli_.set_keep_alive(true);
  6513. auto res = cli_.Get(request.c_str());
  6514. auto end = std::chrono::high_resolution_clock::now();
  6515. auto elapsed =
  6516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6517. .count();
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6520. EXPECT_LE(elapsed, 1000);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. EXPECT_FALSE(cli_.is_socket_open());
  6523. }
  6524. TEST_F(ServerTest, AlmostTooLongRequest) {
  6525. // test for #2046 - URI length check shouldn't include other content on req
  6526. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6527. // leading /, space, HTTP/1.1)
  6528. std::string request =
  6529. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6530. auto res = cli_.Get(request.c_str());
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6533. }
  6534. TEST_F(ServerTest, LongHeader) {
  6535. Request req;
  6536. req.method = "GET";
  6537. req.path = "/hi";
  6538. std::string host_and_port;
  6539. host_and_port += HOST;
  6540. host_and_port += ":";
  6541. host_and_port += std::to_string(PORT);
  6542. req.headers.emplace("Host", host_and_port.c_str());
  6543. req.headers.emplace("Accept", "*/*");
  6544. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6545. req.headers.emplace(
  6546. "Header-Name",
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@");
  6576. auto res = std::make_shared<Response>();
  6577. auto error = Error::Success;
  6578. auto ret = cli_.send(req, *res, error);
  6579. ASSERT_TRUE(ret);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, LongQueryValue) {
  6583. auto start = std::chrono::high_resolution_clock::now();
  6584. cli_.set_keep_alive(true);
  6585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6586. auto end = std::chrono::high_resolution_clock::now();
  6587. auto elapsed =
  6588. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6589. .count();
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6592. EXPECT_LE(elapsed, 1000);
  6593. EXPECT_EQ("close", res->get_header_value("Connection"));
  6594. EXPECT_FALSE(cli_.is_socket_open());
  6595. }
  6596. TEST_F(ServerTest, TooLongQueryValue) {
  6597. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6598. ASSERT_FALSE(res);
  6599. EXPECT_EQ(Error::Read, res.error());
  6600. }
  6601. TEST_F(ServerTest, TooLongHeader) {
  6602. Request req;
  6603. req.method = "GET";
  6604. req.path = "/hi";
  6605. std::string host_and_port;
  6606. host_and_port += HOST;
  6607. host_and_port += ":";
  6608. host_and_port += std::to_string(PORT);
  6609. req.headers.emplace("Host", host_and_port.c_str());
  6610. req.headers.emplace("Accept", "*/*");
  6611. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6612. req.headers.emplace(
  6613. "Header-Name",
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@");
  6643. auto res = std::make_shared<Response>();
  6644. auto error = Error::Success;
  6645. auto ret = cli_.send(req, *res, error);
  6646. ASSERT_TRUE(ret);
  6647. EXPECT_EQ(StatusCode::OK_200, res->status);
  6648. }
  6649. TEST_F(ServerTest, HeaderCountAtLimit) {
  6650. // Test with headers just under the 100 limit
  6651. httplib::Headers headers;
  6652. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6653. // This should keep us just under the 100 header limit
  6654. for (int i = 0; i < 95; i++) {
  6655. std::string name = "X-Test-Header-" + std::to_string(i);
  6656. std::string value = "value" + std::to_string(i);
  6657. headers.emplace(name, value);
  6658. }
  6659. // This should work fine as we're under the limit
  6660. auto res = cli_.Get("/hi", headers);
  6661. EXPECT_TRUE(res);
  6662. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6663. }
  6664. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6665. // Test with many headers to exceed the 100 limit
  6666. httplib::Headers headers;
  6667. // Add 150 headers to definitely exceed the 100 limit
  6668. for (int i = 0; i < 150; i++) {
  6669. std::string name = "X-Test-Header-" + std::to_string(i);
  6670. std::string value = "value" + std::to_string(i);
  6671. headers.emplace(name, value);
  6672. }
  6673. // This should fail due to exceeding header count limit
  6674. cli_.set_keep_alive(true);
  6675. auto res = cli_.Get("/hi", headers);
  6676. // The server should respond with 400 Bad Request
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6679. EXPECT_EQ("close", res->get_header_value("Connection"));
  6680. EXPECT_FALSE(cli_.is_socket_open());
  6681. }
  6682. TEST_F(ServerTest, PercentEncoding) {
  6683. auto res = cli_.Get("/e%6edwith%");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, PercentEncodingUnicode) {
  6688. auto res = cli_.Get("/e%u006edwith%");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. TEST_F(ServerTest, InvalidPercentEncoding) {
  6693. auto res = cli_.Get("/%endwith%");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6698. auto res = cli_.Get("/%uendwith%");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6701. }
  6702. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6703. auto res = cli_.Get("/hello?aaa=bbb%");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6706. }
  6707. TEST_F(ServerTest, PlusSignEncoding) {
  6708. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("a +b", res->body);
  6712. }
  6713. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6714. // This test simulates a potential DoS attack using many headers
  6715. // to verify our security fix prevents memory exhaustion
  6716. httplib::Headers attack_headers;
  6717. // Attempt to add many headers like an attacker would (200 headers to far
  6718. // exceed limit)
  6719. for (int i = 0; i < 200; i++) {
  6720. std::string name = "X-Attack-Header-" + std::to_string(i);
  6721. std::string value = "attack_payload_" + std::to_string(i);
  6722. attack_headers.emplace(name, value);
  6723. }
  6724. // Try to POST with excessive headers
  6725. cli_.set_keep_alive(true);
  6726. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6727. // Should either fail or return 400 Bad Request due to security limit
  6728. if (res) {
  6729. // If we get a response, it should be 400 Bad Request
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ("close", res->get_header_value("Connection"));
  6732. }
  6733. EXPECT_FALSE(cli_.is_socket_open());
  6734. }
  6735. TEST_F(ServerTest, MultipartFormData) {
  6736. UploadFormDataItems items = {
  6737. {"text1", "text default", "", ""},
  6738. {"text2", "aωb", "", ""},
  6739. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6740. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6741. {"file3", "", "", "application/octet-stream"},
  6742. {"file4", "", "", " application/json tmp-string "}};
  6743. auto res = cli_.Post("/multipart", items);
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6748. UploadFormDataItems items = {
  6749. {"text", "default text", "", ""},
  6750. {"multi_text1", "aaaaa", "", ""},
  6751. {"multi_text1", "bbbbb", "", ""},
  6752. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6753. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6754. "application/json"},
  6755. };
  6756. auto res = cli_.Post("/multipart/multi_file_values", items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6761. auto res = cli_.Get("/hi");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6765. EXPECT_EQ("Hello World!", res->body);
  6766. }
  6767. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/chunked";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace("Content-Type", "text/plain");
  6779. req.headers.emplace("Content-Length", "0");
  6780. req.headers.emplace(
  6781. "Transfer-Encoding",
  6782. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6783. // Client does not chunk, so make a chunked body manually.
  6784. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6785. auto res = std::make_shared<Response>();
  6786. auto error = Error::Success;
  6787. auto ret = cli_.send(req, *res, error);
  6788. ASSERT_TRUE(ret);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. template <typename ClientT>
  6792. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6793. int expected_status) {
  6794. Request req;
  6795. req.method = "POST";
  6796. req.path = "/chunked";
  6797. std::string host_and_port;
  6798. host_and_port += HOST;
  6799. host_and_port += ":";
  6800. host_and_port += std::to_string(PORT);
  6801. req.headers.emplace("Host", host_and_port.c_str());
  6802. req.headers.emplace("Content-Length", "0");
  6803. req.headers.emplace("Transfer-Encoding", "chunked");
  6804. req.body = body;
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. ASSERT_TRUE(cli.send(req, *res, error));
  6808. EXPECT_EQ(expected_status, res->status);
  6809. }
  6810. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6811. // rather than treat them as valid lengths.
  6812. template <typename ClientT>
  6813. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6814. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6815. }
  6816. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6817. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6818. }
  6819. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6820. expect_chunked_body_rejected(
  6821. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6822. }
  6823. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6824. // chunk-size line carries no CR, LF or other control character ahead of its
  6825. // terminator. Such a line must be refused rather than read as extension text.
  6826. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6835. expect_chunked_body_rejected(
  6836. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6839. // The literal stays split: a hex escape consumes every hex digit that
  6840. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6841. expect_chunked_body_rejected(
  6842. cli_, "4;a\x01"
  6843. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // The bytes around chunk data are no payload, so they cannot ride on the
  6846. // payload limit
  6847. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6848. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, 'x');
  6849. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, '0');
  6850. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 2, ' ');
  6851. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6852. SCOPED_TRACE(size_line.substr(0, 2));
  6853. std::string body;
  6854. for (auto c : std::string("dechunked post body")) {
  6855. body += size_line + "\r\n" + c + "\r\n";
  6856. }
  6857. body += "0\r\n\r\n";
  6858. expect_chunked_body_rejected(cli_, body.c_str());
  6859. }
  6860. }
  6861. TEST_F(ServerTest, AcceptsChunkExtension) {
  6862. expect_chunked_body_status(cli_,
  6863. "4;name=value\r\ndech\r\n"
  6864. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6865. "0;last\r\n\r\n",
  6866. StatusCode::OK_200);
  6867. }
  6868. TEST_F(ServerTest, GetStreamed2) {
  6869. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6873. EXPECT_EQ(true, res->has_header("Content-Range"));
  6874. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6875. EXPECT_EQ(std::string("ab"), res->body);
  6876. }
  6877. TEST_F(ServerTest, GetStreamed) {
  6878. auto res = cli_.Get("/streamed");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6882. EXPECT_EQ(std::string("aaabbb"), res->body);
  6883. }
  6884. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6885. auto res = cli_.Get("/streamed-without-length",
  6886. Headers{make_range_header({{0, -1}})});
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. EXPECT_EQ(false, res->has_header("Content-Length"));
  6890. EXPECT_EQ(false, res->has_header("Content-Range"));
  6891. EXPECT_EQ(std::string("abcdefg"), res->body);
  6892. }
  6893. TEST_F(ServerTest, GetStreamedWithRange1) {
  6894. auto res =
  6895. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6898. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6899. EXPECT_EQ(true, res->has_header("Content-Range"));
  6900. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6901. EXPECT_EQ(std::string("def"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetStreamedWithRange2) {
  6904. auto res =
  6905. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6908. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6909. EXPECT_EQ(true, res->has_header("Content-Range"));
  6910. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6911. EXPECT_EQ(std::string("bcdefg"), res->body);
  6912. }
  6913. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6914. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6917. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6918. EXPECT_EQ(true, res->has_header("Content-Range"));
  6919. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6920. EXPECT_EQ(std::string("efg"), res->body);
  6921. }
  6922. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6923. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6924. // the entire representation.
  6925. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6926. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6929. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6930. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6931. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6932. }
  6933. }
  6934. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6935. auto res =
  6936. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6939. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6940. EXPECT_EQ(false, res->has_header("Content-Range"));
  6941. EXPECT_EQ(0U, res->body.size());
  6942. }
  6943. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6944. // Only a 206 is served as a partial representation. Under any other status
  6945. // `apply_ranges()` reported the full content length, so the body must match
  6946. // that header, and the content provider must never be asked for an offset
  6947. // outside the representation.
  6948. auto check = [&](int status, const char *range) {
  6949. auto path =
  6950. std::string("/streamed-with-range?status=") + std::to_string(status);
  6951. auto ctx = path + " Range: " + range;
  6952. auto res = cli_.Get(path, Headers{{"Range", range}});
  6953. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6954. EXPECT_EQ(status, res->status) << ctx;
  6955. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6957. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6958. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6959. };
  6960. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6961. check(403, "bytes=3-5");
  6962. // The offset is far past the representation.
  6963. check(403, "bytes=100000-100200");
  6964. // `first_pos` is still -1 here, and the bounds asserts in
  6965. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6966. check(403, "bytes=-3");
  6967. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6968. // multipart branch would have written one that is empty.
  6969. check(403, "bytes=1-2, 4-5");
  6970. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6971. // covers the whole representation.
  6972. check(200, "bytes=3-5");
  6973. check(200, "bytes=1-2, 4-5");
  6974. }
  6975. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6976. auto res =
  6977. cli_.Get("/streamed-with-range",
  6978. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6979. "92233720368547758079223372036854775807"}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6982. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(false, res->has_header("Content-Range"));
  6984. EXPECT_EQ(0U, res->body.size());
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6987. auto res = cli_.Get(
  6988. "/with-range",
  6989. Headers{{"Range",
  6990. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6991. {"Accept-Encoding", ""}});
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6994. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6995. EXPECT_EQ(true, res->has_header("Content-Range"));
  6996. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6997. EXPECT_EQ(std::string("abcdefg"), res->body);
  6998. }
  6999. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7000. auto res = cli_.Get("/with-range", Headers{
  7001. {"Range", "bytes=0-"},
  7002. {"Accept-Encoding", ""},
  7003. });
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7006. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(true, res->has_header("Content-Range"));
  7008. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7009. EXPECT_EQ(std::string("abcdefg"), res->body);
  7010. }
  7011. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7012. auto res = cli_.Get("/streamed-with-range",
  7013. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7016. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7017. EXPECT_EQ(false, res->has_header("Content-Range"));
  7018. EXPECT_EQ(267U, res->body.size());
  7019. // Check that both range contents are present
  7020. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7021. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7022. // Check that Content-Range headers are present for both ranges
  7023. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7024. std::string::npos);
  7025. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7026. std::string::npos);
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7029. Ranges ranges;
  7030. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7031. ranges.emplace_back(0, -1);
  7032. }
  7033. auto res = cli_.Get("/streamed-with-range?error",
  7034. Headers{{make_range_header(ranges)}});
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7037. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7038. EXPECT_EQ(false, res->has_header("Content-Range"));
  7039. EXPECT_EQ(0U, res->body.size());
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(5U, res->body.size());
  7047. // Check that overlapping ranges are coalesced into a single range
  7048. EXPECT_EQ("bcdef", res->body);
  7049. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7050. // Should be single range, not multipart
  7051. EXPECT_TRUE(res->has_header("Content-Range"));
  7052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7053. }
  7054. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7055. auto res = cli_.Get("/streamed-with-range",
  7056. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7059. EXPECT_EQ(268U, res->body.size());
  7060. // Check that both range contents are present
  7061. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7062. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7063. // Check that Content-Range headers are present for both ranges
  7064. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7065. std::string::npos);
  7066. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7067. std::string::npos);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7070. auto res = cli_.Get("/streamed-with-range",
  7071. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ(269U, res->body.size());
  7075. // Check that both duplicate range contents are present
  7076. size_t first_abc = res->body.find("abc\r\n");
  7077. EXPECT_TRUE(first_abc != std::string::npos);
  7078. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7079. EXPECT_TRUE(second_abc != std::string::npos);
  7080. // Check that Content-Range headers are present for both ranges
  7081. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7082. EXPECT_TRUE(first_range != std::string::npos);
  7083. size_t second_range =
  7084. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7085. EXPECT_TRUE(second_range != std::string::npos);
  7086. }
  7087. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7088. auto res =
  7089. cli_.Get("/streamed-with-range?error",
  7090. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7092. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7093. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7094. EXPECT_EQ(false, res->has_header("Content-Range"));
  7095. EXPECT_EQ(0U, res->body.size());
  7096. }
  7097. TEST_F(ServerTest, GetStreamedEndless) {
  7098. uint64_t offset = 0;
  7099. auto res = cli_.Get("/streamed-cancel",
  7100. [&](const char * /*data*/, uint64_t data_length) {
  7101. if (offset < 100) {
  7102. offset += data_length;
  7103. return true;
  7104. }
  7105. return false;
  7106. });
  7107. ASSERT_TRUE(!res);
  7108. EXPECT_EQ(Error::Canceled, res.error());
  7109. }
  7110. TEST_F(ServerTest, ClientStop) {
  7111. std::atomic_size_t count{4};
  7112. std::vector<std::thread> threads;
  7113. for (auto i = count.load(); i != 0; --i) {
  7114. threads.emplace_back([&]() {
  7115. auto res = cli_.Get("/streamed-cancel",
  7116. [&](const char *, uint64_t) { return true; });
  7117. --count;
  7118. ASSERT_TRUE(!res);
  7119. EXPECT_TRUE(res.error() == Error::Canceled ||
  7120. res.error() == Error::Read || res.error() == Error::Write);
  7121. });
  7122. }
  7123. std::this_thread::sleep_for(std::chrono::seconds(2));
  7124. while (count != 0) {
  7125. cli_.stop();
  7126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7127. }
  7128. for (auto &t : threads) {
  7129. t.join();
  7130. }
  7131. }
  7132. TEST_F(ServerTest, GetWithRange1) {
  7133. auto res = cli_.Get("/with-range", Headers{
  7134. make_range_header({{3, 5}}),
  7135. {"Accept-Encoding", ""},
  7136. });
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7139. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(true, res->has_header("Content-Range"));
  7141. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7142. EXPECT_EQ(std::string("def"), res->body);
  7143. }
  7144. TEST_F(ServerTest, GetWithRange2) {
  7145. auto res = cli_.Get("/with-range", Headers{
  7146. make_range_header({{1, -1}}),
  7147. {"Accept-Encoding", ""},
  7148. });
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("bcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetWithRange3) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{0, 0}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("a"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange4) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{-1, 2}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("fg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange5) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 5}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("abcdef"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7193. auto res =
  7194. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7197. }
  7198. TEST_F(ServerTest, GetWithRangeMultipart) {
  7199. auto res =
  7200. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(false, res->has_header("Content-Range"));
  7205. EXPECT_EQ(267U, res->body.size());
  7206. }
  7207. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7208. auto res = cli_.Get("/with-range",
  7209. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7212. }
  7213. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7214. auto res = cli_.Get("/with-range-customized-response",
  7215. Headers{{make_range_header({{1, 2}})}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7218. EXPECT_EQ(true, res->has_header("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(JSON_DATA, res->body);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7223. auto res = cli_.Get("/with-range-customized-response",
  7224. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7227. EXPECT_EQ(true, res->has_header("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(JSON_DATA, res->body);
  7230. }
  7231. TEST_F(ServerTest, Issue1772) {
  7232. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7235. }
  7236. TEST_F(ServerTest, Issue609) {
  7237. auto res = cli_.Delete("/issue609");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ(std::string("ok"), res->body);
  7241. }
  7242. TEST_F(ServerTest, GetStreamedChunked) {
  7243. auto res = cli_.Get("/streamed-chunked");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. EXPECT_EQ(StatusCode::OK_200, res->status);
  7246. EXPECT_EQ(std::string("123456789"), res->body);
  7247. }
  7248. TEST_F(ServerTest, GetStreamedChunked2) {
  7249. auto res = cli_.Get("/streamed-chunked2");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::OK_200, res->status);
  7252. EXPECT_EQ(std::string("123456789"), res->body);
  7253. }
  7254. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7255. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ(std::string("123456789"), res->body);
  7259. EXPECT_TRUE(res->has_header("Trailer"));
  7260. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7261. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7262. // Trailers are now stored separately from headers (security fix)
  7263. EXPECT_EQ(2U, res->trailers.size());
  7264. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7265. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7266. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7267. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7268. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7269. // Verify trailers are NOT in headers (security verification)
  7270. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7271. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7272. }
  7273. TEST_F(ServerTest, LargeChunkedPost) {
  7274. Request req;
  7275. req.method = "POST";
  7276. req.path = "/large-chunked";
  7277. std::string host_and_port;
  7278. host_and_port += HOST;
  7279. host_and_port += ":";
  7280. host_and_port += std::to_string(PORT);
  7281. req.headers.emplace("Host", host_and_port.c_str());
  7282. req.headers.emplace("Accept", "*/*");
  7283. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7284. req.headers.emplace("Content-Type", "text/plain");
  7285. req.headers.emplace("Content-Length", "0");
  7286. req.headers.emplace("Transfer-Encoding", "chunked");
  7287. std::string long_string(30 * 1024u, 'a');
  7288. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7289. // Attempt to make a large enough post to exceed OS buffers, to test that
  7290. // the server handles short reads if the full chunk data isn't available.
  7291. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7299. auto res = cli_.Get("/remote_addr");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7304. }
  7305. TEST_F(ServerTest, GetMethodLocalAddr) {
  7306. auto res = cli_.Get("/local_addr");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7310. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7311. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7312. }
  7313. TEST_F(ServerTest, HTTPResponseSplitting) {
  7314. auto res = cli_.Get("/http_response_splitting");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. }
  7318. TEST_F(ServerTest, SlowRequest) {
  7319. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7320. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7321. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7322. }
  7323. #if 0
  7324. TEST_F(ServerTest, SlowPost) {
  7325. char buffer[64 * 1024];
  7326. memset(buffer, 0x42, sizeof(buffer));
  7327. auto res = cli_.Post(
  7328. "/slowpost", 64 * 1024 * 1024,
  7329. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7330. auto ret = sink.write(buffer, sizeof(buffer));
  7331. EXPECT_TRUE(ret);
  7332. return true;
  7333. },
  7334. "text/plain");
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::OK_200, res->status);
  7337. }
  7338. TEST_F(ServerTest, SlowPostFail) {
  7339. char buffer[64 * 1024];
  7340. memset(buffer, 0x42, sizeof(buffer));
  7341. cli_.set_write_timeout(std::chrono::seconds(0));
  7342. auto res = cli_.Post(
  7343. "/slowpost", 64 * 1024 * 1024,
  7344. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7345. sink.write(buffer, sizeof(buffer));
  7346. return true;
  7347. },
  7348. "text/plain");
  7349. ASSERT_TRUE(!res);
  7350. EXPECT_EQ(Error::Write, res.error());
  7351. }
  7352. #endif
  7353. TEST_F(ServerTest, Put) {
  7354. auto res = cli_.Put("/put", "PUT", "text/plain");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. EXPECT_EQ("PUT", res->body);
  7358. }
  7359. TEST_F(ServerTest, PutWithContentProvider) {
  7360. auto res = cli_.Put(
  7361. "/put", 3,
  7362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7363. sink.os << "PUT";
  7364. return true;
  7365. },
  7366. "text/plain");
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. EXPECT_EQ("PUT", res->body);
  7370. }
  7371. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7372. auto res = cli_.Post(
  7373. "/post", 42,
  7374. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7375. return false;
  7376. },
  7377. "text/plain");
  7378. ASSERT_TRUE(!res);
  7379. EXPECT_EQ(Error::Canceled, res.error());
  7380. }
  7381. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7382. auto res = cli_.Put(
  7383. "/put",
  7384. [](size_t /*offset*/, DataSink &sink) {
  7385. sink.os << "PUT";
  7386. sink.done();
  7387. return true;
  7388. },
  7389. "text/plain");
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. EXPECT_EQ("PUT", res->body);
  7393. }
  7394. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7395. auto res = cli_.Post(
  7396. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7397. "text/plain");
  7398. ASSERT_TRUE(!res);
  7399. EXPECT_EQ(Error::Canceled, res.error());
  7400. }
  7401. TEST_F(ServerTest, PostLoopBack) {
  7402. std::string body;
  7403. auto res = cli_.Post(
  7404. "/post-loopback", 9,
  7405. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7406. EXPECT_EQ(9u, length);
  7407. sink.write("123", 3);
  7408. sink.write("456", 3);
  7409. sink.write("789", 3);
  7410. return true;
  7411. },
  7412. "text/plain",
  7413. [&body](const char *data, size_t data_length) {
  7414. body.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. EXPECT_EQ("123456789", body);
  7420. }
  7421. TEST_F(ServerTest, PutLoopBack) {
  7422. std::string body;
  7423. auto res = cli_.Put(
  7424. "/put-loopback", 9,
  7425. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7426. EXPECT_EQ(9u, length);
  7427. sink.write("123", 3);
  7428. sink.write("456", 3);
  7429. sink.write("789", 3);
  7430. return true;
  7431. },
  7432. "text/plain",
  7433. [&body](const char *data, size_t data_length) {
  7434. body.append(data, data_length);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("123456789", body);
  7440. }
  7441. TEST_F(ServerTest, PatchLoopBack) {
  7442. std::string body;
  7443. auto res = cli_.Patch(
  7444. "/patch-loopback", 9,
  7445. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7446. EXPECT_EQ(9u, length);
  7447. sink.write("123", 3);
  7448. sink.write("456", 3);
  7449. sink.write("789", 3);
  7450. return true;
  7451. },
  7452. "text/plain",
  7453. [&body](const char *data, size_t data_length) {
  7454. body.append(data, data_length);
  7455. return true;
  7456. });
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("123456789", body);
  7460. }
  7461. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7462. std::string body;
  7463. auto res = cli_.Post(
  7464. "/post-loopback",
  7465. [](size_t /*offset*/, DataSink &sink) {
  7466. sink.write("123", 3);
  7467. sink.write("456", 3);
  7468. sink.write("789", 3);
  7469. sink.done();
  7470. return true;
  7471. },
  7472. "text/plain",
  7473. [&body](const char *data, size_t data_length) {
  7474. body.append(data, data_length);
  7475. return true;
  7476. });
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ("123456789", body);
  7480. }
  7481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7482. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Put(
  7485. "/put", 3,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. sink.os << "PUT";
  7488. return true;
  7489. },
  7490. "text/plain");
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ("PUT", res->body);
  7494. }
  7495. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7496. cli_.set_compress(true);
  7497. auto res = cli_.Post(
  7498. "/post", 42,
  7499. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7500. return false;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(!res);
  7504. EXPECT_EQ(Error::Canceled, res.error());
  7505. }
  7506. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put",
  7510. [](size_t /*offset*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. sink.done();
  7513. return true;
  7514. },
  7515. "text/plain");
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. EXPECT_EQ("PUT", res->body);
  7519. }
  7520. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7521. cli_.set_compress(true);
  7522. auto res = cli_.Post(
  7523. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7524. "text/plain");
  7525. ASSERT_TRUE(!res);
  7526. EXPECT_EQ(Error::Canceled, res.error());
  7527. }
  7528. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7529. cli_.set_compress(true);
  7530. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ(LARGE_DATA, res->body);
  7534. }
  7535. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7536. #ifdef CPPHTTPLIB_SSL_ENABLED
  7537. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7538. Client cli(s.c_str());
  7539. cli.enable_server_certificate_verification(false);
  7540. #else
  7541. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7542. Client cli(s.c_str());
  7543. #endif
  7544. cli.set_compress(true);
  7545. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. EXPECT_EQ(LARGE_DATA, res->body);
  7549. // The compressed size should be less than a 10th of the original. May vary
  7550. // depending on the zlib library.
  7551. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7552. static_cast<uint64_t>(10 * 1024 * 1024));
  7553. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7554. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7555. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7556. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7557. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7558. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7559. #endif
  7560. }
  7561. TEST_F(ServerTest, PutContentWithDeflate) {
  7562. cli_.set_compress(false);
  7563. Headers headers;
  7564. headers.emplace("Content-Encoding", "deflate");
  7565. // PUT in deflate format:
  7566. auto res = cli_.Put("/put", headers,
  7567. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("PUT", res->body);
  7571. }
  7572. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7573. Headers headers;
  7574. headers.emplace("Accept-Encoding", "gzip, deflate");
  7575. auto res = cli_.Get("/streamed-chunked", headers);
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::OK_200, res->status);
  7578. EXPECT_EQ(std::string("123456789"), res->body);
  7579. }
  7580. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7581. Headers headers;
  7582. headers.emplace("Accept-Encoding", "gzip, deflate");
  7583. auto res = cli_.Get("/streamed-chunked2", headers);
  7584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7585. EXPECT_EQ(StatusCode::OK_200, res->status);
  7586. EXPECT_EQ(std::string("123456789"), res->body);
  7587. }
  7588. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7589. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::OK_200, res->status);
  7592. }
  7593. TEST(GzipDecompressor, ChunkedDecompression) {
  7594. std::string data;
  7595. for (size_t i = 0; i < 32 * 1024; ++i) {
  7596. data.push_back(static_cast<char>('a' + i % 26));
  7597. }
  7598. std::string compressed_data;
  7599. {
  7600. httplib::detail::gzip_compressor compressor;
  7601. bool result = compressor.compress(
  7602. data.data(), data.size(),
  7603. /*last=*/true,
  7604. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7605. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7606. compressed_data_size);
  7607. return true;
  7608. });
  7609. ASSERT_TRUE(result);
  7610. }
  7611. std::string decompressed_data;
  7612. {
  7613. httplib::detail::gzip_decompressor decompressor;
  7614. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7615. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7616. size_t chunk_size = 130;
  7617. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7618. chunk_begin += chunk_size) {
  7619. size_t current_chunk_size =
  7620. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7621. bool result = decompressor.decompress(
  7622. compressed_data.data() + chunk_begin, current_chunk_size,
  7623. [&](const char *decompressed_data_chunk,
  7624. size_t decompressed_data_chunk_size) {
  7625. decompressed_data.insert(decompressed_data.size(),
  7626. decompressed_data_chunk,
  7627. decompressed_data_chunk_size);
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(result);
  7631. }
  7632. }
  7633. ASSERT_EQ(data, decompressed_data);
  7634. }
  7635. TEST(GzipDecompressor, DeflateDecompression) {
  7636. std::string original_text = "Raw deflate without gzip";
  7637. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7638. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7639. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7640. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7641. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7642. std::string decompressed_data;
  7643. {
  7644. httplib::detail::gzip_decompressor decompressor;
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data(), compressed_data.size(),
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. ASSERT_EQ(original_text, decompressed_data);
  7657. }
  7658. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7659. std::string original_text = "Raw deflate without gzip";
  7660. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7661. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7662. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7663. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7664. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. #endif
  7683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7684. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7685. Headers headers;
  7686. headers.emplace("Accept-Encoding", "br");
  7687. auto res = cli_.Get("/streamed-chunked", headers);
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(std::string("123456789"), res->body);
  7691. }
  7692. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7693. Headers headers;
  7694. headers.emplace("Accept-Encoding", "br");
  7695. auto res = cli_.Get("/streamed-chunked2", headers);
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(std::string("123456789"), res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put", 3,
  7704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. return true;
  7707. },
  7708. "text/plain");
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::OK_200, res->status);
  7711. EXPECT_EQ("PUT", res->body);
  7712. }
  7713. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7714. cli_.set_compress(true);
  7715. auto res = cli_.Put(
  7716. "/put",
  7717. [](size_t /*offset*/, DataSink &sink) {
  7718. sink.os << "PUT";
  7719. sink.done();
  7720. return true;
  7721. },
  7722. "text/plain");
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("PUT", res->body);
  7726. }
  7727. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7728. cli_.set_compress(true);
  7729. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ(LARGE_DATA, res->body);
  7733. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7734. }
  7735. #endif
  7736. TEST_F(ServerTest, Patch) {
  7737. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_EQ("PATCH", res->body);
  7741. }
  7742. TEST_F(ServerTest, Delete) {
  7743. auto res = cli_.Delete("/delete");
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::OK_200, res->status);
  7746. EXPECT_EQ("DELETE", res->body);
  7747. }
  7748. TEST_F(ServerTest, DeleteContentReceiver) {
  7749. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. EXPECT_EQ("content", res->body);
  7753. }
  7754. TEST_F(ServerTest, Options) {
  7755. auto res = cli_.Options("*");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7759. EXPECT_TRUE(res->body.empty());
  7760. }
  7761. TEST_F(ServerTest, URL) {
  7762. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. }
  7766. TEST_F(ServerTest, ArrayParam) {
  7767. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, ArrayParamValues) {
  7772. auto res =
  7773. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. }
  7777. TEST_F(ServerTest, NoMultipleHeaders) {
  7778. Headers headers = {{"Content-Length", "5"}};
  7779. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7780. "text/plain");
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. }
  7784. TEST_F(ServerTest, PostContentReceiver) {
  7785. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. ASSERT_EQ(StatusCode::OK_200, res->status);
  7788. ASSERT_EQ("content", res->body);
  7789. }
  7790. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7791. UploadFormDataItems items = {
  7792. {"text1", "text default", "", ""},
  7793. {"text2", "aωb", "", ""},
  7794. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7795. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7796. {"file3", "", "", "application/octet-stream"},
  7797. };
  7798. auto res = cli_.Post("/content_receiver", items);
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. }
  7802. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7803. UploadFormDataItems items = {
  7804. {"text1", "text default", "", ""},
  7805. {"text2", "aωb", "", ""},
  7806. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7807. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7808. {"file3", "", "", "application/octet-stream"},
  7809. };
  7810. auto boundary = std::string("+++++");
  7811. std::string body;
  7812. for (const auto &item : items) {
  7813. body += "--" + boundary + "\r\n";
  7814. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7815. if (!item.filename.empty()) {
  7816. body += "; filename=\"" + item.filename + "\"";
  7817. }
  7818. body += "\r\n";
  7819. if (!item.content_type.empty()) {
  7820. body += "Content-Type: " + item.content_type + "\r\n";
  7821. }
  7822. body += "\r\n";
  7823. body += item.content + "\r\n";
  7824. }
  7825. body += "--" + boundary + "--\r\n";
  7826. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7827. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ(StatusCode::OK_200, res->status);
  7830. }
  7831. TEST(MultipartFormDataTest, FieldEscaping) {
  7832. Server svr;
  7833. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7834. const ContentReader &content_reader) {
  7835. ASSERT_TRUE(req.is_multipart_form_data());
  7836. std::vector<FormData> received;
  7837. content_reader(
  7838. [&](const FormData &file) {
  7839. received.push_back(file);
  7840. return true;
  7841. },
  7842. [&](const char *data, size_t data_length) {
  7843. received.back().content.append(data, data_length);
  7844. return true;
  7845. });
  7846. // '"', CR and LF in names and filenames are escaped following the
  7847. // WHATWG HTML standard, so each part still parses as a single part
  7848. // with no injected headers. Content types get CR/LF escaped too,
  7849. // while '"' (legal there, e.g. quoted charset) is preserved.
  7850. ASSERT_EQ(4U, received.size());
  7851. EXPECT_EQ("na%22me", received[0].name);
  7852. EXPECT_EQ("quoted name", received[0].content);
  7853. EXPECT_EQ("file", received[1].name);
  7854. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7855. received[1].filename);
  7856. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7857. EXPECT_EQ("injected", received[1].content);
  7858. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7859. EXPECT_EQ("my%22file.txt", received[2].filename);
  7860. EXPECT_EQ("cr lf name", received[2].content);
  7861. EXPECT_EQ("typed", received[3].name);
  7862. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7863. received[3].content_type);
  7864. EXPECT_EQ("typed content", received[3].content);
  7865. });
  7866. auto port = svr.bind_to_any_port("localhost");
  7867. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7868. auto se = detail::scope_exit([&] {
  7869. svr.stop();
  7870. t.join();
  7871. ASSERT_FALSE(svr.is_running());
  7872. });
  7873. svr.wait_until_ready();
  7874. Client cli("localhost", port);
  7875. UploadFormDataItems items = {
  7876. {"na\"me", "quoted name", "", ""},
  7877. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7878. "application/octet-stream"},
  7879. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7880. {"typed", "typed content", "",
  7881. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7882. };
  7883. auto res = cli.Post("/post", items);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. }
  7887. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7888. const UploadFormDataItems items = {
  7889. {"name1", "Content 1", "", ""},
  7890. {"name2", "Content 2", "file2.txt", "text/plain"},
  7891. };
  7892. Server svr;
  7893. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7894. const ContentReader &content_reader) {
  7895. ASSERT_TRUE(req.is_multipart_form_data());
  7896. std::vector<FormData> received;
  7897. content_reader(
  7898. [&](const FormData &file) {
  7899. received.push_back(file);
  7900. return true;
  7901. },
  7902. [&](const char *data, size_t data_length) {
  7903. received.back().content.append(data, data_length);
  7904. return true;
  7905. });
  7906. ASSERT_EQ(2U, received.size());
  7907. EXPECT_EQ("name1", received[0].name);
  7908. EXPECT_EQ("Content 1", received[0].content);
  7909. EXPECT_EQ("name2", received[1].name);
  7910. EXPECT_EQ("Content 2", received[1].content);
  7911. EXPECT_EQ("file2.txt", received[1].filename);
  7912. EXPECT_EQ("text/plain", received[1].content_type);
  7913. });
  7914. auto port = svr.bind_to_any_port("localhost");
  7915. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7916. auto se = detail::scope_exit([&] {
  7917. svr.stop();
  7918. t.join();
  7919. ASSERT_FALSE(svr.is_running());
  7920. });
  7921. svr.wait_until_ready();
  7922. Client cli("localhost", port);
  7923. // Whole-body serialization with a generated boundary
  7924. {
  7925. MultipartFormDataWriter writer;
  7926. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7927. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7928. writer.content_type());
  7929. auto body = writer.serialize(items);
  7930. EXPECT_EQ(body.size(), writer.content_length(items));
  7931. auto res = cli.Post("/post", body, writer.content_type());
  7932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. // Per-part framing with a custom boundary via a content provider
  7936. {
  7937. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7938. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7939. MultipartFormDataWriter writer("custom-boundary_123");
  7940. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7941. std::string body;
  7942. for (const auto &item : items) {
  7943. body += writer.item_begin(item);
  7944. body += item.content;
  7945. body += MultipartFormDataWriter::item_end();
  7946. }
  7947. body += writer.finish();
  7948. EXPECT_EQ(body.size(), writer.content_length(items));
  7949. auto res = cli.Post(
  7950. "/post", body.size(),
  7951. [&](size_t offset, size_t length, DataSink &sink) {
  7952. sink.write(body.data() + offset, length);
  7953. return true;
  7954. },
  7955. writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. }
  7960. TEST_F(ServerTest, PostContentReceiverGzip) {
  7961. cli_.set_compress(true);
  7962. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. ASSERT_EQ(StatusCode::OK_200, res->status);
  7965. ASSERT_EQ("content", res->body);
  7966. }
  7967. TEST_F(ServerTest, PutContentReceiver) {
  7968. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. ASSERT_EQ(StatusCode::OK_200, res->status);
  7971. ASSERT_EQ("content", res->body);
  7972. }
  7973. TEST_F(ServerTest, PatchContentReceiver) {
  7974. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. ASSERT_EQ(StatusCode::OK_200, res->status);
  7977. ASSERT_EQ("content", res->body);
  7978. }
  7979. template <typename ClientType>
  7980. void TestWithHeadersAndContentReceiver(
  7981. ClientType &cli,
  7982. std::function<Result(ClientType &, const std::string &, const Headers &,
  7983. const std::string &, const std::string &,
  7984. ContentReceiver, DownloadProgress)>
  7985. request_func) {
  7986. Headers headers;
  7987. headers.emplace("X-Custom-Header", "test-value");
  7988. std::string received_body;
  7989. auto res = request_func(
  7990. cli, "/content_receiver", headers, "content", "application/json",
  7991. [&](const char *data, size_t data_length) {
  7992. received_body.append(data, data_length);
  7993. return true;
  7994. },
  7995. nullptr);
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ("content", received_body);
  7999. }
  8000. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Post(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Put(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8027. #ifdef CPPHTTPLIB_SSL_ENABLED
  8028. using ClientT = SSLClient;
  8029. #else
  8030. using ClientT = Client;
  8031. #endif
  8032. TestWithHeadersAndContentReceiver<ClientT>(
  8033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8034. const std::string &body, const std::string &content_type,
  8035. ContentReceiver receiver, DownloadProgress progress) {
  8036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8037. });
  8038. }
  8039. template <typename ClientType>
  8040. void TestWithHeadersAndContentReceiverWithProgress(
  8041. ClientType &cli,
  8042. std::function<Result(ClientType &, const std::string &, const Headers &,
  8043. const std::string &, const std::string &,
  8044. ContentReceiver, DownloadProgress)>
  8045. request_func) {
  8046. Headers headers;
  8047. headers.emplace("X-Test-Header", "progress-test");
  8048. std::string received_body;
  8049. auto progress_called = false;
  8050. auto res = request_func(
  8051. cli, "/content_receiver", headers, "content", "text/plain",
  8052. [&](const char *data, size_t data_length) {
  8053. received_body.append(data, data_length);
  8054. return true;
  8055. },
  8056. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8057. progress_called = true;
  8058. return true;
  8059. });
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("content", received_body);
  8063. EXPECT_TRUE(progress_called);
  8064. }
  8065. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Post(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Put(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8092. #ifdef CPPHTTPLIB_SSL_ENABLED
  8093. using ClientT = SSLClient;
  8094. #else
  8095. using ClientT = Client;
  8096. #endif
  8097. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8099. const std::string &body, const std::string &content_type,
  8100. ContentReceiver receiver, DownloadProgress progress) {
  8101. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8102. });
  8103. }
  8104. template <typename ClientType>
  8105. void TestWithHeadersAndContentReceiverError(
  8106. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8107. const Headers &, const std::string &,
  8108. const std::string &, ContentReceiver)>
  8109. request_func) {
  8110. Headers headers;
  8111. headers.emplace("X-Error-Test", "true");
  8112. std::string received_body;
  8113. auto receiver_failed = false;
  8114. auto res =
  8115. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8116. [&](const char *data, size_t data_length) {
  8117. received_body.append(data, data_length);
  8118. receiver_failed = true;
  8119. return false;
  8120. });
  8121. ASSERT_FALSE(res);
  8122. EXPECT_TRUE(receiver_failed);
  8123. }
  8124. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Post(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Put(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8151. #ifdef CPPHTTPLIB_SSL_ENABLED
  8152. using ClientT = SSLClient;
  8153. #else
  8154. using ClientT = Client;
  8155. #endif
  8156. TestWithHeadersAndContentReceiverError<ClientT>(
  8157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8158. const std::string &body, const std::string &content_type,
  8159. ContentReceiver receiver) {
  8160. return cli.Patch(path, headers, body, content_type, receiver);
  8161. });
  8162. }
  8163. TEST_F(ServerTest, PostQueryStringAndBody) {
  8164. auto res =
  8165. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. ASSERT_EQ(StatusCode::OK_200, res->status);
  8168. }
  8169. TEST_F(ServerTest, HTTP2Magic) {
  8170. Request req;
  8171. req.method = "PRI";
  8172. req.path = "*";
  8173. req.body = "SM";
  8174. auto res = std::make_shared<Response>();
  8175. auto error = Error::Success;
  8176. auto ret = cli_.send(req, *res, error);
  8177. ASSERT_TRUE(ret);
  8178. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8179. }
  8180. TEST_F(ServerTest, KeepAlive) {
  8181. auto res = cli_.Get("/hi");
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8185. EXPECT_EQ("Hello World!", res->body);
  8186. res = cli_.Get("/hi");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("Hello World!", res->body);
  8191. res = cli_.Get("/hi");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8195. EXPECT_EQ("Hello World!", res->body);
  8196. res = cli_.Get("/not-exist");
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8199. res = cli_.Post("/empty", "", "text/plain");
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8203. EXPECT_EQ("empty", res->body);
  8204. EXPECT_EQ("close", res->get_header_value("Connection"));
  8205. res = cli_.Post(
  8206. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8207. "text/plain");
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8211. EXPECT_EQ("empty", res->body);
  8212. cli_.set_keep_alive(false);
  8213. res = cli_.Get("/last-request");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("close", res->get_header_value("Connection"));
  8217. }
  8218. TEST_F(ServerTest, TooManyRedirect) {
  8219. cli_.set_follow_location(true);
  8220. auto res = cli_.Get("/redirect/0");
  8221. ASSERT_TRUE(!res);
  8222. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8223. }
  8224. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8225. Request req;
  8226. req.method = "FOOBAR";
  8227. req.path = "/hi";
  8228. cli_.set_keep_alive(true);
  8229. auto res = cli_.send(req);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8232. EXPECT_EQ("close", res->get_header_value("Connection"));
  8233. EXPECT_FALSE(cli_.is_socket_open());
  8234. }
  8235. TEST_F(ServerTest, CustomRouteReadsBody) {
  8236. const std::string xml =
  8237. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/dir";
  8241. req.set_header("Depth", "1");
  8242. req.body = xml;
  8243. auto res = cli_.send(req);
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8246. EXPECT_EQ(xml, res->body);
  8247. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8248. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8249. }
  8250. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8251. Request req;
  8252. req.method = "PROPFIND";
  8253. req.path = "/dav/42";
  8254. auto res = cli_.send(req);
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8257. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8258. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8259. }
  8260. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8261. Request req;
  8262. req.method = "PROPFIND";
  8263. req.path = "/dav-re/123";
  8264. auto res = cli_.send(req);
  8265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8266. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8267. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8268. }
  8269. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8270. Request req;
  8271. req.method = "MKCOL";
  8272. req.path = "/dav-mkcol";
  8273. auto res = cli_.send(req);
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(StatusCode::Created_201, res->status);
  8276. }
  8277. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8278. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. req.body = xml;
  8283. auto res = cli_.send(req);
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8286. EXPECT_EQ(xml, res->body);
  8287. }
  8288. // A content reader route must fire even when the request carries no body,
  8289. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8290. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8291. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8292. Request req;
  8293. req.method = "REPORT";
  8294. req.path = "/dav-report";
  8295. auto res = cli_.send(req);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8298. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8299. }
  8300. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8301. Request req;
  8302. req.method = "PROPFIND";
  8303. req.path = "/not-dav";
  8304. auto res = cli_.send(req);
  8305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8307. }
  8308. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8309. Request req;
  8310. req.method = "UNLOCK";
  8311. req.path = "/dav/dir";
  8312. cli_.set_keep_alive(true);
  8313. auto res = cli_.send(req);
  8314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8315. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8316. EXPECT_EQ("close", res->get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. }
  8319. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8320. // The mount point serves this path, but only for GET and HEAD.
  8321. auto get_res = cli_.Get("/dir/index.html");
  8322. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8323. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8324. Request req;
  8325. req.method = "PROPFIND";
  8326. req.path = "/dir/index.html";
  8327. auto res = cli_.send(req);
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8330. }
  8331. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8332. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8333. cli_.set_keep_alive(true);
  8334. for (auto i = 0; i < 2; i++) {
  8335. Request req;
  8336. req.method = "PROPFIND";
  8337. req.path = "/dav/dir";
  8338. req.body = xml;
  8339. auto res = cli_.send(req);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8342. EXPECT_EQ(xml, res->body);
  8343. EXPECT_TRUE(cli_.is_socket_open());
  8344. }
  8345. // A built-in method must still be served on the same connection.
  8346. cli_.set_keep_alive(false);
  8347. auto res = cli_.Get("/hi");
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::OK_200, res->status);
  8350. EXPECT_EQ("close", res->get_header_value("Connection"));
  8351. }
  8352. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8353. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8354. Request req;
  8355. req.method = "PROPFIND";
  8356. req.path = "/dav/dir";
  8357. req.set_header("Expect", "100-continue");
  8358. req.body = xml;
  8359. auto res = cli_.send(req);
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8362. EXPECT_EQ(xml, res->body);
  8363. }
  8364. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8366. TEST_F(ServerTest, Gzip) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "gzip, deflate");
  8382. auto res = cli_.Get("/compress-with-charset", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8385. EXPECT_EQ("application/json; charset=utf-8",
  8386. res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "");
  8395. auto res = cli_.Get("/compress", headers);
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8399. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8401. "7890123456789012345678901234567890",
  8402. res->body);
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST_F(ServerTest, GzipWithContentReceiver) {
  8406. Headers headers;
  8407. headers.emplace("Accept-Encoding", "gzip, deflate");
  8408. std::string body;
  8409. auto res =
  8410. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8411. EXPECT_EQ(100U, data_length);
  8412. body.append(data, data_length);
  8413. return true;
  8414. });
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8418. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8420. "7890123456789012345678901234567890",
  8421. body);
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. }
  8424. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "gzip, deflate");
  8427. cli_.set_decompress(false);
  8428. auto res = cli_.Get("/compress", headers);
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ(33U, res->body.size());
  8434. EXPECT_EQ(StatusCode::OK_200, res->status);
  8435. }
  8436. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8437. Headers headers;
  8438. headers.emplace("Accept-Encoding", "");
  8439. std::string body;
  8440. auto res =
  8441. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8442. EXPECT_EQ(100U, data_length);
  8443. body.append(data, data_length);
  8444. return true;
  8445. });
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzip) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. auto res = cli_.Get("/nocompress", headers);
  8459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8464. "7890123456789012345678901234567890",
  8465. res->body);
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8469. Headers headers;
  8470. headers.emplace("Accept-Encoding", "gzip, deflate");
  8471. std::string body;
  8472. auto res = cli_.Get("/nocompress", headers,
  8473. [&](const char *data, size_t data_length) {
  8474. EXPECT_EQ(100U, data_length);
  8475. body.append(data, data_length);
  8476. return true;
  8477. });
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8480. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8481. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8482. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8483. "7890123456789012345678901234567890",
  8484. body);
  8485. EXPECT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST_F(ServerTest, MultipartFormDataGzip) {
  8488. UploadFormDataItems items = {
  8489. {"key1", "test", "", ""},
  8490. {"key2", "--abcdefg123", "", ""},
  8491. };
  8492. cli_.set_compress(true);
  8493. auto res = cli_.Post("/compress-multipart", items);
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. #endif
  8498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8499. // Static file compression is opt-in, so these run their own server rather than
  8500. // flipping it on for the shared ServerTest fixture, which would silently
  8501. // rewrite what every other static file test is asserting.
  8502. class StaticFileCompressionTest : public ::testing::Test {
  8503. protected:
  8504. void TearDown() override {
  8505. if (t_.joinable()) {
  8506. svr_.stop();
  8507. t_.join();
  8508. }
  8509. }
  8510. int start(const std::function<void(Server &)> &configure = nullptr) {
  8511. // Serves the same tree as a directory of build-time compressed assets
  8512. // would be served: the mount point names the coding the files are already
  8513. // stored in. Registered before "/" so it is the one that matches.
  8514. svr_.set_mount_point("/pre-encoded", "./www",
  8515. {{"Content-Encoding", "gzip"}});
  8516. svr_.set_mount_point("/", "./www");
  8517. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8518. res.set_file_content("./www/dir/index.html", "text/html");
  8519. });
  8520. svr_.Get("/pre-encoded-file-content",
  8521. [](const Request & /*req*/, Response &res) {
  8522. res.set_header("Content-Encoding", "gzip");
  8523. res.set_file_content("./www/dir/index.html", "text/html");
  8524. });
  8525. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8526. res.set_content_provider(
  8527. 6, "text/plain",
  8528. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8529. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8530. return true;
  8531. });
  8532. });
  8533. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8534. res.set_content_provider(
  8535. 1000, "text/plain",
  8536. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8537. if (offset < 100) {
  8538. std::string data(100, 'A');
  8539. sink.write(data.data(), data.size());
  8540. return true;
  8541. }
  8542. std::this_thread::sleep_for(std::chrono::seconds(2));
  8543. std::string data(900, 'B');
  8544. sink.write(data.data(), data.size());
  8545. return true;
  8546. });
  8547. });
  8548. if (configure) { configure(svr_); }
  8549. auto port = svr_.bind_to_any_port(HOST);
  8550. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8551. svr_.wait_until_ready();
  8552. return port;
  8553. }
  8554. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8555. // Every file under ./www except 1MB.txt is smaller than the default
  8556. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8557. // it out of the way.
  8558. static void enable_without_floor(Server &svr) {
  8559. svr.set_static_file_compression(true);
  8560. svr.set_static_file_compression_min_length(0);
  8561. }
  8562. Server svr_;
  8563. std::thread t_;
  8564. };
  8565. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8566. auto port = start();
  8567. Client cli(HOST, port);
  8568. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::OK_200, res->status);
  8571. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8572. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8573. EXPECT_EQ(1048576U, res->body.size());
  8574. }
  8575. TEST_F(StaticFileCompressionTest, MountPoint) {
  8576. auto port = start(enable);
  8577. Client cli(HOST, port);
  8578. cli.set_decompress(false);
  8579. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8583. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8584. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8585. // The response stays self-delimiting: a length, not a chunked body.
  8586. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8587. EXPECT_EQ(std::to_string(res->body.size()),
  8588. res->get_header_value("Content-Length"));
  8589. EXPECT_LT(res->body.size(), 1048576U);
  8590. EXPECT_FALSE(res->body.empty());
  8591. }
  8592. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8593. auto port = start(enable);
  8594. Client cli(HOST, port);
  8595. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ(StatusCode::OK_200, res->status);
  8598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8599. EXPECT_EQ(1048576U, res->body.size());
  8600. }
  8601. TEST_F(StaticFileCompressionTest, FileContent) {
  8602. auto port = start(enable_without_floor);
  8603. Client cli(HOST, port);
  8604. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::OK_200, res->status);
  8607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. EXPECT_EQ(104U, res->body.size());
  8610. }
  8611. // A handler that serves an already-encoded file names the coding itself. The
  8612. // file-backed path decided its coding from Accept-Encoding and the content
  8613. // type alone, so it compressed the stored bytes a second time and appended a
  8614. // second Content-Encoding field line.
  8615. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8616. auto port = start(enable_without_floor);
  8617. Client cli(HOST, port);
  8618. cli.set_decompress(false);
  8619. auto res = cli.Get("/pre-encoded-file-content",
  8620. Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8625. // Vary belongs to a coding the server chose, and it chose none here.
  8626. EXPECT_FALSE(res->has_header("Vary"));
  8627. // The file travels exactly as it is stored on disk.
  8628. EXPECT_EQ(104U, res->body.size());
  8629. }
  8630. // The 1MB file clears the default floor, so this one runs the configuration a
  8631. // deployment would actually have.
  8632. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8633. auto port = start(enable);
  8634. Client cli(HOST, port);
  8635. cli.set_decompress(false);
  8636. auto res =
  8637. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8642. EXPECT_FALSE(res->has_header("Vary"));
  8643. EXPECT_EQ(1048576U, res->body.size());
  8644. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8645. }
  8646. TEST_F(StaticFileCompressionTest, Head) {
  8647. auto port = start(enable);
  8648. Client cli(HOST, port);
  8649. cli.set_decompress(false);
  8650. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8652. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8656. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8657. // HEAD still reports the size a GET would return.
  8658. EXPECT_EQ(get->get_header_value("Content-Length"),
  8659. res->get_header_value("Content-Length"));
  8660. EXPECT_TRUE(res->body.empty());
  8661. }
  8662. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8663. auto port = start(enable);
  8664. Client cli(HOST, port);
  8665. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8666. {"Accept-Encoding", "gzip"}});
  8667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8668. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8669. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8670. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8671. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8672. EXPECT_EQ("cd", res->body);
  8673. }
  8674. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8675. auto port = start(enable);
  8676. Client cli(HOST, port);
  8677. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8679. EXPECT_EQ(StatusCode::OK_200, res->status);
  8680. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8681. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8682. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8683. }
  8684. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8685. auto port = start(enable);
  8686. Client cli(HOST, port);
  8687. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8691. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8692. EXPECT_TRUE(res->body.empty());
  8693. }
  8694. TEST_F(StaticFileCompressionTest, MinLength) {
  8695. auto port = start(enable);
  8696. Client cli(HOST, port);
  8697. // 104 bytes, well under the default floor. Compressing it would add the
  8698. // gzip header and trailer to a body that already fits in one packet.
  8699. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8703. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8704. }
  8705. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8706. auto port = start([](Server &svr) {
  8707. svr.set_static_file_compression(true);
  8708. svr.set_static_file_compression_min_length(1);
  8709. });
  8710. Client cli(HOST, port);
  8711. cli.set_decompress(false);
  8712. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8715. // A 9-byte file comes back larger than it went in, because gzip's header and
  8716. // trailer outweigh anything deflate can save. That is the end of the range
  8717. // the floor exists to keep out.
  8718. EXPECT_GT(res->body.size(), 9U);
  8719. }
  8720. TEST_F(StaticFileCompressionTest, MaxLength) {
  8721. auto port = start([](Server &svr) {
  8722. svr.set_static_file_compression(true);
  8723. svr.set_static_file_compression_min_length(0);
  8724. svr.set_static_file_compression_max_length(1024);
  8725. });
  8726. Client cli(HOST, port);
  8727. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8728. // defines `small` as a macro on Windows.
  8729. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8731. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8732. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8733. // Under it: compressed.
  8734. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8736. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8737. }
  8738. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8739. auto port = start(enable_without_floor);
  8740. Client cli(HOST, port);
  8741. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8742. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8743. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8744. auto identity_etag = identity->get_header_value("ETag");
  8745. ASSERT_FALSE(identity_etag.empty());
  8746. auto gzipped =
  8747. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8748. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8749. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8750. auto gzip_etag = gzipped->get_header_value("ETag");
  8751. ASSERT_FALSE(gzip_etag.empty());
  8752. // Two representations, two validators.
  8753. EXPECT_NE(identity_etag, gzip_etag);
  8754. // Each one revalidates against the request that would produce it...
  8755. auto fresh =
  8756. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8757. {"If-None-Match", gzip_etag}});
  8758. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8759. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8760. auto fresh_identity =
  8761. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8762. {"If-None-Match", identity_etag}});
  8763. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8764. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8765. // ...and not against the other representation.
  8766. auto crossed =
  8767. cli.Get("/dir/index.html",
  8768. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8769. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8770. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8771. }
  8772. // The opt-in covers responses the server reads off disk itself. A caller's own
  8773. // known-length provider keeps its Content-Length and, more importantly, keeps
  8774. // delivering incrementally: routing it through a compressor would hold every
  8775. // write back until zlib's window filled.
  8776. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8777. auto port = start(enable);
  8778. Client cli(HOST, port);
  8779. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8781. EXPECT_EQ(StatusCode::OK_200, res->status);
  8782. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8784. EXPECT_EQ("aaabbb", res->body);
  8785. }
  8786. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8787. auto port = start(enable);
  8788. Client cli(HOST, port);
  8789. cli.set_read_timeout(1, 0);
  8790. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8791. Headers{{"Accept-Encoding", "gzip"}});
  8792. ASSERT_TRUE(handle.is_valid());
  8793. // The provider writes 100 bytes and then stalls for longer than the read
  8794. // timeout. Those first bytes have to arrive anyway: run the response through
  8795. // a compressor and zlib holds them until its window fills, so the read would
  8796. // come back empty instead.
  8797. char buf[256];
  8798. auto n = handle.read(buf, sizeof(buf));
  8799. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8800. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8801. }
  8802. #endif
  8803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8804. TEST_F(ServerTest, Brotli) {
  8805. Headers headers;
  8806. headers.emplace("Accept-Encoding", "br");
  8807. auto res = cli_.Get("/compress", headers);
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8811. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8812. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8813. "7890123456789012345678901234567890",
  8814. res->body);
  8815. EXPECT_EQ(StatusCode::OK_200, res->status);
  8816. }
  8817. #endif
  8818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8819. TEST_F(ServerTest, Zstd) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "zstd");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "");
  8835. auto res = cli_.Get("/compress", headers);
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8839. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8840. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8841. "7890123456789012345678901234567890",
  8842. res->body);
  8843. EXPECT_EQ(StatusCode::OK_200, res->status);
  8844. }
  8845. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8846. Headers headers;
  8847. headers.emplace("Accept-Encoding", "zstd");
  8848. std::string body;
  8849. auto res =
  8850. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8851. EXPECT_EQ(100U, data_length);
  8852. body.append(data, data_length);
  8853. return true;
  8854. });
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8858. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8859. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8860. "7890123456789012345678901234567890",
  8861. body);
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. }
  8864. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8865. Headers headers;
  8866. headers.emplace("Accept-Encoding", "zstd");
  8867. cli_.set_decompress(false);
  8868. auto res = cli_.Get("/compress", headers);
  8869. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8870. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8871. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8872. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8874. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8876. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. ASSERT_EQ(26U, res->body.size());
  8879. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8880. 0);
  8881. }
  8882. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8883. Headers headers;
  8884. headers.emplace("Accept-Encoding", "");
  8885. std::string body;
  8886. auto res =
  8887. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8888. EXPECT_EQ(100U, data_length);
  8889. body.append(data, data_length);
  8890. return true;
  8891. });
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8894. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstd) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. auto res = cli_.Get("/nocompress", headers);
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8907. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8908. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8909. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8910. "7890123456789012345678901234567890",
  8911. res->body);
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8915. Headers headers;
  8916. headers.emplace("Accept-Encoding", "zstd");
  8917. std::string body;
  8918. auto res = cli_.Get("/nocompress", headers,
  8919. [&](const char *data, size_t data_length) {
  8920. EXPECT_EQ(100U, data_length);
  8921. body.append(data, data_length);
  8922. return true;
  8923. });
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8929. "7890123456789012345678901234567890",
  8930. body);
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. // TODO: How to enable zstd ??
  8934. TEST_F(ServerTest, MultipartFormDataZstd) {
  8935. UploadFormDataItems items = {
  8936. {"key1", "test", "", ""},
  8937. {"key2", "--abcdefg123", "", ""},
  8938. };
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. cli_.set_compress(true);
  8942. auto res = cli_.Post("/compress-multipart", headers, items);
  8943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8944. EXPECT_EQ(StatusCode::OK_200, res->status);
  8945. }
  8946. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8947. Headers headers;
  8948. headers.emplace("Accept-Encoding", "zstd");
  8949. cli_.set_compress(true);
  8950. auto res = cli_.Put(
  8951. "/put", headers, 3,
  8952. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8953. sink.os << "PUT";
  8954. return true;
  8955. },
  8956. "text/plain");
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("PUT", res->body);
  8960. }
  8961. // Pre-compression logging tests
  8962. TEST_F(ServerTest, PreCompressionLogging) {
  8963. // Test data for compression (matches the actual /compress endpoint content)
  8964. const std::string test_content =
  8965. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8966. "3456789012345678901234567890";
  8967. // Variables to capture logging data
  8968. std::string pre_compression_body;
  8969. std::string pre_compression_content_type;
  8970. std::string pre_compression_content_encoding;
  8971. std::string post_compression_body;
  8972. std::string post_compression_content_type;
  8973. std::string post_compression_content_encoding;
  8974. // Set up pre-compression logger
  8975. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8976. const Response &res) {
  8977. pre_compression_body = res.body;
  8978. pre_compression_content_type = res.get_header_value("Content-Type");
  8979. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8980. });
  8981. // Set up post-compression logger
  8982. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8983. post_compression_body = res.body;
  8984. post_compression_content_type = res.get_header_value("Content-Type");
  8985. post_compression_content_encoding =
  8986. res.get_header_value("Content-Encoding");
  8987. });
  8988. // Test with gzip compression
  8989. Headers headers;
  8990. headers.emplace("Accept-Encoding", "gzip");
  8991. auto res = cli_.Get("/compress", headers);
  8992. // Verify response was compressed
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8996. // Verify pre-compression logger captured uncompressed content
  8997. EXPECT_EQ(test_content, pre_compression_body);
  8998. EXPECT_EQ("text/plain", pre_compression_content_type);
  8999. EXPECT_TRUE(pre_compression_content_encoding
  9000. .empty()); // No encoding header before compression
  9001. // Verify post-compression logger captured compressed content
  9002. EXPECT_NE(test_content,
  9003. post_compression_body); // Should be different after compression
  9004. EXPECT_EQ("text/plain", post_compression_content_type);
  9005. EXPECT_EQ("gzip", post_compression_content_encoding);
  9006. // Verify compressed content is smaller
  9007. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9008. }
  9009. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9010. const std::string test_content =
  9011. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9012. "3456789012345678901234567890";
  9013. std::string pre_compression_body;
  9014. std::string post_compression_body;
  9015. svr_.set_pre_compression_logger(
  9016. [&](const Request & /*req*/, const Response &res) {
  9017. pre_compression_body = res.body;
  9018. });
  9019. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9020. post_compression_body = res.body;
  9021. });
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "br");
  9024. auto res = cli_.Get("/compress", headers);
  9025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9026. EXPECT_EQ(StatusCode::OK_200, res->status);
  9027. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9028. // Verify pre-compression content is uncompressed
  9029. EXPECT_EQ(test_content, pre_compression_body);
  9030. // Verify post-compression content is compressed
  9031. EXPECT_NE(test_content, post_compression_body);
  9032. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9033. }
  9034. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9035. const std::string test_content =
  9036. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9037. "3456789012345678901234567890";
  9038. std::string pre_compression_body;
  9039. std::string post_compression_body;
  9040. svr_.set_pre_compression_logger(
  9041. [&](const Request & /*req*/, const Response &res) {
  9042. pre_compression_body = res.body;
  9043. });
  9044. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9045. post_compression_body = res.body;
  9046. });
  9047. // Request without compression (use /nocompress endpoint)
  9048. Headers headers;
  9049. auto res = cli_.Get("/nocompress", headers);
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9053. // Pre-compression logger should not be called when no compression is applied
  9054. EXPECT_TRUE(
  9055. pre_compression_body.empty()); // Pre-compression logger not called
  9056. EXPECT_EQ(
  9057. test_content,
  9058. post_compression_body); // Post-compression logger captures final content
  9059. }
  9060. TEST_F(ServerTest, LoggerSeesContentLength) {
  9061. size_t logged_content_length = 0;
  9062. std::string logged_content_length_header;
  9063. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9064. logged_content_length = res.content_length_;
  9065. logged_content_length_header = res.get_header_value("Content-Length");
  9066. });
  9067. auto res = cli_.Get("/nocompress");
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. EXPECT_EQ(res->body.size(), logged_content_length);
  9071. EXPECT_EQ(std::to_string(logged_content_length),
  9072. logged_content_length_header);
  9073. }
  9074. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9075. const std::string test_content =
  9076. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9077. "3456789012345678901234567890";
  9078. std::string pre_compression_body;
  9079. bool pre_logger_called = false;
  9080. // Set only pre-compression logger
  9081. svr_.set_pre_compression_logger(
  9082. [&](const Request & /*req*/, const Response &res) {
  9083. pre_compression_body = res.body;
  9084. pre_logger_called = true;
  9085. });
  9086. Headers headers;
  9087. headers.emplace("Accept-Encoding", "gzip");
  9088. auto res = cli_.Get("/compress", headers);
  9089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9092. // Verify pre-compression logger was called
  9093. EXPECT_TRUE(pre_logger_called);
  9094. EXPECT_EQ(test_content, pre_compression_body);
  9095. }
  9096. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9097. {
  9098. // Test with Expect: 100-continue header - success case
  9099. // Server returns 100 Continue, client sends body, server returns 200 OK
  9100. Request req;
  9101. req.method = "POST";
  9102. req.path = "/post-large";
  9103. req.set_header("Expect", "100-continue");
  9104. req.body = LARGE_DATA;
  9105. Response res;
  9106. auto error = Error::Success;
  9107. cli_.set_keep_alive(true);
  9108. auto ret = cli_.send(req, res, error);
  9109. EXPECT_TRUE(ret);
  9110. EXPECT_EQ(StatusCode::OK_200, res.status);
  9111. EXPECT_EQ(LARGE_DATA, res.body);
  9112. }
  9113. {
  9114. // Test with Expect: 100-continue header - error case
  9115. // Client should not send the body when server returns an error
  9116. Request req;
  9117. req.method = "POST";
  9118. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9119. req.set_header("Expect", "100-continue");
  9120. req.body = LARGE_DATA;
  9121. Response res;
  9122. auto error = Error::Success;
  9123. auto start = std::chrono::high_resolution_clock::now();
  9124. cli_.set_keep_alive(true);
  9125. auto ret = cli_.send(req, res, error);
  9126. auto end = std::chrono::high_resolution_clock::now();
  9127. auto elapsed =
  9128. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9129. .count();
  9130. // With Expect: 100-continue, request completes successfully but with error
  9131. EXPECT_TRUE(ret);
  9132. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9133. EXPECT_EQ("close", res.get_header_value("Connection"));
  9134. EXPECT_FALSE(cli_.is_socket_open());
  9135. EXPECT_LE(elapsed, 2000);
  9136. }
  9137. {
  9138. // Send an extra GET request to ensure error recovery without hanging
  9139. Request req;
  9140. req.method = "GET";
  9141. req.path = "/hi";
  9142. auto start = std::chrono::high_resolution_clock::now();
  9143. auto res = cli_.send(req);
  9144. auto end = std::chrono::high_resolution_clock::now();
  9145. auto elapsed =
  9146. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9147. .count();
  9148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9149. EXPECT_EQ(StatusCode::OK_200, res->status);
  9150. EXPECT_EQ("Hello World!", res->body);
  9151. EXPECT_LE(elapsed, 500);
  9152. }
  9153. }
  9154. TEST(ZstdDecompressor, ChunkedDecompression) {
  9155. std::string data;
  9156. for (size_t i = 0; i < 32 * 1024; ++i) {
  9157. data.push_back(static_cast<char>('a' + i % 26));
  9158. }
  9159. std::string compressed_data;
  9160. {
  9161. httplib::detail::zstd_compressor compressor;
  9162. bool result = compressor.compress(
  9163. data.data(), data.size(),
  9164. /*last=*/true,
  9165. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9166. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9167. compressed_data_size);
  9168. return true;
  9169. });
  9170. ASSERT_TRUE(result);
  9171. }
  9172. std::string decompressed_data;
  9173. {
  9174. httplib::detail::zstd_decompressor decompressor;
  9175. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9176. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9177. size_t chunk_size = 130;
  9178. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9179. chunk_begin += chunk_size) {
  9180. size_t current_chunk_size =
  9181. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9182. bool result = decompressor.decompress(
  9183. compressed_data.data() + chunk_begin, current_chunk_size,
  9184. [&](const char *decompressed_data_chunk,
  9185. size_t decompressed_data_chunk_size) {
  9186. decompressed_data.insert(decompressed_data.size(),
  9187. decompressed_data_chunk,
  9188. decompressed_data_chunk_size);
  9189. return true;
  9190. });
  9191. ASSERT_TRUE(result);
  9192. }
  9193. }
  9194. ASSERT_EQ(data, decompressed_data);
  9195. }
  9196. TEST(ZstdDecompressor, Decompress) {
  9197. std::string original_text = "Compressed with ZSTD";
  9198. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9199. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9200. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9201. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9202. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9203. std::string decompressed_data;
  9204. {
  9205. httplib::detail::zstd_decompressor decompressor;
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data(), compressed_data.size(),
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. ASSERT_EQ(original_text, decompressed_data);
  9218. }
  9219. #endif
  9220. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9221. // separate chunks so that the server sees each part in its own read(). Used to
  9222. // place a read boundary at a specific offset of a request body.
  9223. static bool send_request_in_parts(time_t read_timeout_sec,
  9224. const std::vector<std::string> &parts,
  9225. std::string *resp = nullptr,
  9226. int port = PORT) {
  9227. auto error = Error::Success;
  9228. auto client_sock = detail::create_client_socket(
  9229. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9230. /*connection_timeout_sec=*/5, 0,
  9231. /*read_timeout_sec=*/5, 0,
  9232. /*write_timeout_sec=*/5, 0, std::string(), error);
  9233. if (client_sock == INVALID_SOCKET) { return false; }
  9234. auto ret = detail::process_client_socket(
  9235. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9236. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9237. for (size_t i = 0; i < parts.size(); i++) {
  9238. const auto &part = parts[i];
  9239. if (part.size() !=
  9240. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9241. return false;
  9242. }
  9243. if (i + 1 < parts.size()) {
  9244. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9245. }
  9246. }
  9247. char buf[512];
  9248. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9249. while (line_reader.getline()) {
  9250. if (resp) { *resp += line_reader.ptr(); }
  9251. }
  9252. return true;
  9253. });
  9254. detail::close_socket(client_sock);
  9255. return ret;
  9256. }
  9257. // Sends a raw request to a server listening at HOST:PORT.
  9258. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9259. std::string *resp = nullptr, int port = PORT) {
  9260. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9261. }
  9262. #ifdef CPPHTTPLIB_SSL_ENABLED
  9263. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9265. ASSERT_TRUE(svr.is_valid());
  9266. svr.set_read_timeout(1, 0);
  9267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. t.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. svr.wait_until_ready();
  9274. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9275. // keeps each wait well within the read timeout. The server gives up a
  9276. // second in, so the bytes sent after that fail.
  9277. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9278. parts.resize(26, std::string(1, '\0'));
  9279. EXPECT_FALSE(send_request_in_parts(5, parts));
  9280. }
  9281. #endif
  9282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9283. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9284. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9285. const std::vector<std::string> &parts,
  9286. std::string *resp = nullptr,
  9287. int port = PORT) {
  9288. auto error = Error::Success;
  9289. auto sock = detail::create_client_socket(
  9290. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9291. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9292. /*write_timeout_sec=*/5, 0, std::string(), error);
  9293. if (sock == INVALID_SOCKET) { return false; }
  9294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9295. auto ctx = SSL_CTX_new(TLS_client_method());
  9296. auto ssl = SSL_new(ctx);
  9297. auto ssl_se = detail::scope_exit([&] {
  9298. SSL_free(ssl);
  9299. SSL_CTX_free(ctx);
  9300. });
  9301. SSL_set_fd(ssl, static_cast<int>(sock));
  9302. if (SSL_connect(ssl) != 1) { return false; }
  9303. for (size_t i = 0; i < parts.size(); i++) {
  9304. const auto &part = parts[i];
  9305. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9306. static_cast<int>(part.size())) {
  9307. return false;
  9308. }
  9309. if (i + 1 < parts.size()) {
  9310. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9311. }
  9312. }
  9313. char buf[512];
  9314. int n;
  9315. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9316. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9317. }
  9318. return true;
  9319. }
  9320. #endif
  9321. // The request line, then a header value a byte at a time.
  9322. static std::vector<std::string> slow_request_head_parts() {
  9323. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9324. parts.resize(26, "a");
  9325. parts.emplace_back("\r\n\r\n");
  9326. return parts;
  9327. }
  9328. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9329. // within the one-second read timeout. The server gives up a second in, before
  9330. // the head is complete.
  9331. static void
  9332. expect_slow_request_head_dropped(Server &svr,
  9333. const std::function<std::string()> &send) {
  9334. std::atomic<bool> handled(false);
  9335. svr.Get("/", [&](const Request &, Response &res) {
  9336. handled = true;
  9337. res.set_content("ok", "text/plain");
  9338. });
  9339. svr.set_read_timeout(1, 0);
  9340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9341. auto se = detail::scope_exit([&] {
  9342. svr.stop();
  9343. t.join();
  9344. ASSERT_FALSE(svr.is_running());
  9345. });
  9346. svr.wait_until_ready();
  9347. auto resp = send();
  9348. EXPECT_FALSE(handled);
  9349. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9350. }
  9351. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9352. Server svr;
  9353. expect_slow_request_head_dropped(svr, [] {
  9354. std::string resp;
  9355. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9356. return resp;
  9357. });
  9358. }
  9359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9360. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9362. ASSERT_TRUE(svr.is_valid());
  9363. expect_slow_request_head_dropped(svr, [] {
  9364. std::string resp;
  9365. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9366. return resp;
  9367. });
  9368. }
  9369. #endif
  9370. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9371. Server svr;
  9372. std::string header_value;
  9373. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9374. header_value = req.get_header_value("foo");
  9375. res.set_content("ok", "text/plain");
  9376. });
  9377. thread t = thread([&] { svr.listen(HOST, PORT); });
  9378. auto se = detail::scope_exit([&] {
  9379. svr.stop();
  9380. t.join();
  9381. ASSERT_FALSE(svr.is_running());
  9382. });
  9383. svr.wait_until_ready();
  9384. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9385. // like characters are not treated the same - use vertical tab and escape.
  9386. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9387. "foo: \t \v bar \x1B\t \r\n"
  9388. "Connection: close\r\n"
  9389. "\r\n";
  9390. std::string res;
  9391. ASSERT_TRUE(send_request(5, req, &res));
  9392. EXPECT_EQ(header_value, "");
  9393. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9394. }
  9395. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9396. Server svr;
  9397. std::string received;
  9398. svr.Get("/order", [&](const Request &req, Response &res) {
  9399. received = entries_to_string(req.headers);
  9400. res.set_content("ok", "text/plain");
  9401. });
  9402. auto port = svr.bind_to_any_port(HOST);
  9403. thread t = thread([&] { svr.listen_after_bind(); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. t.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. const std::string req = "GET /order HTTP/1.1\r\n"
  9411. "Host: localhost\r\n"
  9412. "X-First: 1\r\n"
  9413. "X-Dup: a\r\n"
  9414. "X-Second: 2\r\n"
  9415. "X-Dup: b\r\n"
  9416. "Connection: close\r\n"
  9417. "\r\n";
  9418. std::string res;
  9419. ASSERT_TRUE(send_request(5, req, &res, port));
  9420. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9421. EXPECT_EQ(
  9422. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9423. received);
  9424. }
  9425. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9426. Server svr;
  9427. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9428. res.set_header("Set-Cookie", "first=1");
  9429. res.set_header("X-Between", "y");
  9430. res.set_header("Set-Cookie", "second=2");
  9431. res.set_content("ok", "text/plain");
  9432. });
  9433. auto port = svr.bind_to_any_port(HOST);
  9434. thread t = thread([&] { svr.listen_after_bind(); });
  9435. auto se = detail::scope_exit([&] {
  9436. svr.stop();
  9437. t.join();
  9438. ASSERT_FALSE(svr.is_running());
  9439. });
  9440. svr.wait_until_ready();
  9441. Client cli(HOST, port);
  9442. auto res = cli.Get("/cookies");
  9443. ASSERT_TRUE(res);
  9444. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9445. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9446. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9447. }
  9448. // A stream may send a byte at a time with a small extension on each chunk,
  9449. // however long it runs
  9450. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9451. Server svr;
  9452. svr.Post("/count", [](const Request &req, Response &res) {
  9453. res.set_content(std::to_string(req.body.size()), "text/plain");
  9454. });
  9455. auto port = svr.bind_to_any_port(HOST);
  9456. ASSERT_LT(0, port);
  9457. thread t = thread([&] { svr.listen_after_bind(); });
  9458. auto se = detail::scope_exit([&] {
  9459. svr.stop();
  9460. t.join();
  9461. ASSERT_FALSE(svr.is_running());
  9462. });
  9463. svr.wait_until_ready();
  9464. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9465. "\r\nTransfer-Encoding: chunked\r\n"
  9466. "Connection: close\r\n\r\n";
  9467. for (auto i = 0; i < 4096; i++) {
  9468. req += "1;a=b\r\nx\r\n";
  9469. }
  9470. req += "0\r\n\r\n";
  9471. std::string res;
  9472. ASSERT_TRUE(send_request(5, req, &res, port));
  9473. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9474. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9475. }
  9476. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9477. Server svr;
  9478. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9479. auto i = new int(0);
  9480. res.set_header("Trailer", "X-Safe, X-Reflected");
  9481. res.set_chunked_content_provider(
  9482. "text/plain",
  9483. [i](size_t /*offset*/, DataSink &sink) {
  9484. if (*i == 0) {
  9485. sink.os << "body";
  9486. } else {
  9487. Headers trailer;
  9488. // A valid trailer that must survive.
  9489. trailer.emplace("X-Safe", "safe");
  9490. // Attacker-controlled value carrying CR/LF (response splitting).
  9491. trailer.emplace("X-Reflected",
  9492. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9493. // Attacker-controlled name carrying CR/LF.
  9494. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9495. sink.done_with_trailer(trailer);
  9496. }
  9497. (*i)++;
  9498. return true;
  9499. },
  9500. [i](bool /*success*/) { delete i; });
  9501. });
  9502. thread t = thread([&] { svr.listen(HOST, PORT); });
  9503. auto se = detail::scope_exit([&] {
  9504. svr.stop();
  9505. t.join();
  9506. ASSERT_FALSE(svr.is_running());
  9507. });
  9508. svr.wait_until_ready();
  9509. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9510. "Host: " + HOST +
  9511. "\r\n"
  9512. "Connection: close\r\n"
  9513. "\r\n";
  9514. std::string res;
  9515. ASSERT_TRUE(send_request(5, req, &res));
  9516. // The injected fields must not appear anywhere in the raw response.
  9517. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9518. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9519. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9520. // Invalid trailers are dropped entirely, matching set_header().
  9521. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9522. // The valid trailer still passes through.
  9523. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9524. }
  9525. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9526. // A custom header writer gets only the fields the default one writes
  9527. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9528. std::string s;
  9529. for (const auto &h : hdrs) {
  9530. s += h.first + ": " + h.second + "\r\n";
  9531. }
  9532. s += "\r\n";
  9533. return strm.write(s.data(), s.size());
  9534. };
  9535. for (auto custom_writer : {false, true}) {
  9536. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9537. Server svr;
  9538. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9539. svr.set_post_routing_handler([](const Request &, Response &res) {
  9540. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9541. });
  9542. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9543. // res.headers is a public field an application can populate directly,
  9544. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9545. // A valid header that must survive.
  9546. res.headers.emplace("X-Safe", "safe");
  9547. // Attacker-controlled value carrying CR/LF (response splitting).
  9548. res.headers.emplace("X-Reflected",
  9549. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9550. // Attacker-controlled name carrying CR/LF.
  9551. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9552. res.set_content("body", "text/plain");
  9553. });
  9554. thread t = thread([&] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9562. "Host: " + HOST +
  9563. "\r\n"
  9564. "Connection: close\r\n"
  9565. "\r\n";
  9566. std::string res;
  9567. ASSERT_TRUE(send_request(5, req, &res));
  9568. // The injected fields must not appear anywhere in the raw response.
  9569. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9570. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9571. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9572. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9573. // Invalid headers are dropped entirely, matching set_header().
  9574. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9575. // The valid header still passes through.
  9576. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9577. }
  9578. }
  9579. // Forward declaration: in split builds split.py strips `inline` and moves the
  9580. // definition into httplib.cc, so detail::write_request_line is not visible from
  9581. // the public httplib.h. Re-declaring it here lets the tests link against the
  9582. // symbol in both header-only and split builds.
  9583. namespace httplib {
  9584. namespace detail {
  9585. ssize_t write_request_line(Stream &strm, const std::string &method,
  9586. const std::string &path);
  9587. } // namespace detail
  9588. } // namespace httplib
  9589. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9590. // A well-formed target is written verbatim.
  9591. {
  9592. detail::BufferStream strm;
  9593. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9594. EXPECT_GT(n, 0);
  9595. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9596. }
  9597. // A target carrying CR/LF, SP or other control octets must be rejected
  9598. // before anything reaches the wire, otherwise it splits the request line and
  9599. // injects a header or a whole request.
  9600. const std::string evil_targets[] = {
  9601. "/a\r\nInjected: pwned",
  9602. "/a\rInjected",
  9603. "/a\nInjected",
  9604. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9605. "/a b",
  9606. "/a\tb",
  9607. "/a\x7f",
  9608. };
  9609. for (const auto &evil : evil_targets) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, "GET", evil);
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9617. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9618. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9619. // target reaches write_request. The client must fail cleanly with
  9620. // Error::Write instead of putting a request-line-less, header-injecting
  9621. // request on the wire.
  9622. Server svr;
  9623. svr.Get("/a", [](const Request &, Response &res) {
  9624. res.set_content("ok", "text/plain");
  9625. });
  9626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. thread.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. {
  9634. Client cli(HOST, PORT);
  9635. cli.set_path_encode(false);
  9636. // The request is rejected before anything is written, so the connection
  9637. // stays silent and the subsequent response read would otherwise block for
  9638. // the full default read timeout. Shorten it -- the assertion is on the
  9639. // error, not the timeout.
  9640. cli.set_read_timeout(1, 0);
  9641. auto res = cli.Get("/a\r\nInjected: pwned");
  9642. EXPECT_FALSE(res);
  9643. EXPECT_EQ(Error::Write, res.error());
  9644. }
  9645. }
  9646. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9647. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9648. // including extension methods.
  9649. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9650. for (const auto &method : good_methods) {
  9651. detail::BufferStream strm;
  9652. auto n = detail::write_request_line(strm, method, "/");
  9653. EXPECT_GT(n, 0);
  9654. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9655. }
  9656. // A method carrying CR/LF would split the request line and smuggle a whole
  9657. // request ahead of the real one. A space or an empty method corrupts the
  9658. // request line. All must be rejected before anything reaches the wire.
  9659. const std::string evil_methods[] = {
  9660. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9661. "GET\r\nInjected: pwned",
  9662. "GET\r",
  9663. "GET\n",
  9664. "GE T",
  9665. "",
  9666. };
  9667. for (const auto &evil : evil_methods) {
  9668. detail::BufferStream strm;
  9669. auto n = detail::write_request_line(strm, evil, "/");
  9670. EXPECT_LT(n, 0);
  9671. EXPECT_TRUE(strm.get_buffer().empty());
  9672. }
  9673. }
  9674. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9675. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9676. // through Client::send must fail with Error::Write and no request, neither
  9677. // the smuggled one nor the real one, may reach the server.
  9678. Server svr;
  9679. std::atomic<int> request_count(0);
  9680. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9681. request_count++;
  9682. res.status = StatusCode::OK_200;
  9683. return Server::HandlerResponse::Handled;
  9684. });
  9685. auto port = svr.bind_to_any_port(HOST);
  9686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9687. auto se = detail::scope_exit([&] {
  9688. svr.stop();
  9689. thread.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. });
  9692. svr.wait_until_ready();
  9693. {
  9694. Client cli(HOST, port);
  9695. const std::string evil_methods[] = {
  9696. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9697. "GE T",
  9698. "",
  9699. };
  9700. for (const auto &evil : evil_methods) {
  9701. Request req;
  9702. req.method = evil;
  9703. req.path = "/";
  9704. auto res = cli.send(req);
  9705. EXPECT_FALSE(res);
  9706. EXPECT_EQ(Error::Write, res.error());
  9707. }
  9708. auto handle =
  9709. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9710. EXPECT_FALSE(handle.is_valid());
  9711. EXPECT_EQ(Error::Write, handle.error);
  9712. // A valid request on the same client still goes through.
  9713. auto res = cli.Get("/");
  9714. ASSERT_TRUE(res);
  9715. EXPECT_EQ(StatusCode::OK_200, res->status);
  9716. }
  9717. EXPECT_EQ(1, request_count.load());
  9718. }
  9719. // Sends a raw request and verifies that there isn't a crash or exception.
  9720. static void test_raw_request(const std::string &req,
  9721. std::string *out = nullptr) {
  9722. Server svr;
  9723. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9724. res.set_content("ok", "text/plain");
  9725. });
  9726. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9727. res.set_content("ok", "text/plain");
  9728. });
  9729. svr.Get("/header_field_value_check",
  9730. [&](const Request & /*req*/, Response &res) {
  9731. res.set_content("ok", "text/plain");
  9732. });
  9733. svr.CustomRoute("PROPFIND", "/dav",
  9734. [&](const Request & /*req*/, Response &res) {
  9735. res.status = StatusCode::MultiStatus_207;
  9736. });
  9737. // Server read timeout must be longer than the client read timeout for the
  9738. // bug to reproduce, probably to force the server to process a request
  9739. // without a trailing blank line.
  9740. const time_t client_read_timeout_sec = 1;
  9741. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9742. bool listen_thread_ok = false;
  9743. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9744. auto se = detail::scope_exit([&] {
  9745. svr.stop();
  9746. t.join();
  9747. ASSERT_FALSE(svr.is_running());
  9748. EXPECT_TRUE(listen_thread_ok);
  9749. });
  9750. svr.wait_until_ready();
  9751. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9752. }
  9753. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9754. // A certain header line causes an exception if the header property is parsed
  9755. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9756. test_raw_request(
  9757. "GET /hi HTTP/1.1\r\n"
  9758. " : "
  9759. " "
  9760. " ");
  9761. }
  9762. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9763. // A certain header line causes an exception if the header property *name* is
  9764. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9765. // greedy matcher and requires backtracking when there are a lot of ":"
  9766. // characters.
  9767. // This occurs with libc++ but not libstdc++.
  9768. test_raw_request(
  9769. "GET /hi HTTP/1.1\r\n"
  9770. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9771. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9772. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9773. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9774. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9775. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9776. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9777. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9778. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9779. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9780. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9781. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9782. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9783. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9784. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9785. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9786. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9787. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9788. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9789. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9790. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9791. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9792. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9793. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9794. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9795. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9796. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9797. "&&&%%%");
  9798. }
  9799. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9800. // Make sure this doesn't crash the server.
  9801. // In a previous version of the header line regex, the "\r" rendered the line
  9802. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9803. // a new position where the leading white space ended and the field value
  9804. // began.
  9805. // The crash occurs with libc++ but not libstdc++.
  9806. test_raw_request("GET /hi HTTP/1.1\r\n"
  9807. "a:" +
  9808. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9809. "\r\n"
  9810. "\r\n");
  9811. }
  9812. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9813. const char *rejected[] = {
  9814. // RFC 9112 §3: one SP between the parts, and nothing else
  9815. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9816. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9817. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9819. // A request-target has no fragment
  9820. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9821. // An HTTP/1.1 request needs a Host
  9822. "GET /hi HTTP/1.1\r\n\r\n",
  9823. };
  9824. for (auto request : rejected) {
  9825. std::string out;
  9826. test_raw_request(request, &out);
  9827. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9828. }
  9829. std::string out;
  9830. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9831. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9832. }
  9833. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9834. // RFC 9112 §6.1
  9835. const char *requests[] = {
  9836. "PUT /put_hi HTTP/1.1\r\n"
  9837. "Host: localhost\r\n"
  9838. "Content-Length: 0\r\n"
  9839. "Transfer-Encoding: chunked\r\n"
  9840. "\r\n"
  9841. "0\r\n\r\n",
  9842. "PUT /put_hi HTTP/1.0\r\n"
  9843. "Connection: keep-alive\r\n"
  9844. "Transfer-Encoding: chunked\r\n"
  9845. "\r\n"
  9846. "0\r\n\r\n",
  9847. };
  9848. for (auto request : requests) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9852. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9853. }
  9854. }
  9855. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9856. std::string out;
  9857. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9858. "Content-Type: text/plain\r\n"
  9859. "Transfer-Encoding: chunked\r\n"
  9860. "\r\n"
  9861. "nothex\r\n",
  9862. &out);
  9863. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9864. }
  9865. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9866. std::string out;
  9867. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9868. "Content-Type: text/plain\r\n"
  9869. "Transfer-Encoding: chunked\r\n"
  9870. "\r\n"
  9871. "3\r\n"
  9872. "xyz\r\n"
  9873. "NaN\r\n",
  9874. &out);
  9875. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9876. }
  9877. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9878. std::string out;
  9879. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9880. "Content-Type: text/plain\r\n"
  9881. "Transfer-Encoding: chunked\r\n"
  9882. "\r\n"
  9883. // Length is too large for 64 bits.
  9884. "1ffffffffffffffff\r\n"
  9885. "xyz\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9890. test_raw_request("GET /hi HTTP/1.1\r\n"
  9891. "Content-Type: text/plain\r\n\r");
  9892. }
  9893. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9894. std::string out;
  9895. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9896. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9897. }
  9898. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9899. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9900. std::string out;
  9901. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9903. }
  9904. }
  9905. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9906. std::string out;
  9907. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9908. "Host: localhost\r\n"
  9909. "Connection: close\r\n\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9912. }
  9913. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9914. Server svr;
  9915. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9916. EXPECT_TRUE(!req.remote_addr.empty());
  9917. });
  9918. thread t = thread([&] { svr.listen(HOST, PORT); });
  9919. auto se = detail::scope_exit([&] {
  9920. svr.stop();
  9921. t.join();
  9922. ASSERT_FALSE(svr.is_running());
  9923. });
  9924. svr.wait_until_ready();
  9925. // Send an invalid request line to trigger Bad Request
  9926. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9927. std::string out;
  9928. ASSERT_TRUE(send_request(5, bad_req, &out));
  9929. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9930. }
  9931. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9932. // answered right away rather than blocking on a read that waits for EOF.
  9933. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9934. std::string out;
  9935. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9936. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9937. }
  9938. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9939. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9940. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9941. for (const auto *method : methods) {
  9942. Server svr;
  9943. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9944. EXPECT_FALSE(svr.is_valid()) << method;
  9945. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9946. }
  9947. }
  9948. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9949. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9950. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9951. for (const auto *method : methods) {
  9952. Server svr;
  9953. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9954. EXPECT_FALSE(svr.is_valid()) << method;
  9955. }
  9956. }
  9957. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9958. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9959. "COPY", "MOVE", "LOCK",
  9960. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9961. Server svr;
  9962. for (const auto *method : methods) {
  9963. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9964. }
  9965. EXPECT_TRUE(svr.is_valid());
  9966. }
  9967. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9968. Server svr;
  9969. svr.CustomRoute("POST", "/x",
  9970. [](const Request &, Response &, const ContentReader &) {});
  9971. EXPECT_FALSE(svr.is_valid());
  9972. }
  9973. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9974. Server svr;
  9975. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9976. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9977. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid());
  9979. }
  9980. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9981. Server svr;
  9982. auto captured = Error::Success;
  9983. svr.set_error_logger(
  9984. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9985. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9986. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9987. }
  9988. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9989. std::string out;
  9990. std::string request(
  9991. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9992. test_raw_request(request, &out);
  9993. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9994. }
  9995. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9996. std::string out;
  9997. std::string request(
  9998. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9999. test_raw_request(request, &out);
  10000. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10001. }
  10002. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10003. std::string out;
  10004. std::string request(
  10005. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10006. test_raw_request(request, &out);
  10007. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10008. }
  10009. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10010. std::string out;
  10011. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10012. "Host: localhost\r\n"
  10013. "Test: \r\n\r\n",
  10014. &out);
  10015. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10016. }
  10017. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10018. Server svr;
  10019. std::string x_custom;
  10020. std::string cookie;
  10021. std::string xff;
  10022. std::string x_unicode;
  10023. std::string x_iis;
  10024. svr.Get("/check", [&](const Request &req, Response &res) {
  10025. x_custom = req.get_header_value("X-Custom");
  10026. cookie = req.get_header_value("Cookie");
  10027. xff = req.get_header_value("X-Forwarded-For");
  10028. x_unicode = req.get_header_value("X-Unicode");
  10029. x_iis = req.get_header_value("X-IIS");
  10030. res.set_content("ok", "text/plain");
  10031. });
  10032. thread t = thread([&] { svr.listen(HOST, PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. const std::string req = "GET /check HTTP/1.1\r\n"
  10040. "Host: localhost\r\n"
  10041. "X-Custom: a%0D%0AInjected: b\r\n"
  10042. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10043. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10044. "X-Unicode: %E3%81%82\r\n"
  10045. "X-IIS: %u00E9\r\n"
  10046. "Connection: close\r\n"
  10047. "\r\n";
  10048. std::string res;
  10049. ASSERT_TRUE(send_request(5, req, &res));
  10050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10051. // Every value must be returned verbatim (wire form), with no decoding.
  10052. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10053. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10054. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10055. EXPECT_EQ("%E3%81%82", x_unicode);
  10056. EXPECT_EQ("%u00E9", x_iis);
  10057. }
  10058. // Applications that previously relied on automatic percent-decoding can
  10059. // reproduce the old behavior by explicitly calling decode_path_component()
  10060. // or, for RFC 3986 conformance, decode_uri_component().
  10061. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10062. Server svr;
  10063. std::string decoded;
  10064. svr.Get("/check", [&](const Request &req, Response &res) {
  10065. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10066. res.set_content("ok", "text/plain");
  10067. });
  10068. thread t = thread([&] { svr.listen(HOST, PORT); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. const std::string req = "GET /check HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "X-Custom: hello%20world\r\n"
  10078. "Connection: close\r\n"
  10079. "\r\n";
  10080. std::string res;
  10081. ASSERT_TRUE(send_request(5, req, &res));
  10082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10083. EXPECT_EQ("hello world", decoded);
  10084. }
  10085. // Regression test for #2033. Browsers send Referer values that include
  10086. // percent-encoded characters such as %0A inside the URL. Decoding the
  10087. // header value would either trip the post-decode CR/LF/NUL guard (the
  10088. // original bug, returning 400) or, after that guard was relaxed, silently
  10089. // store a literal LF — both unacceptable. The wire form must round-trip.
  10090. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10091. Server svr;
  10092. std::string referer;
  10093. svr.Get("/check", [&](const Request &req, Response &res) {
  10094. referer = req.get_header_value("Referer");
  10095. res.set_content("ok", "text/plain");
  10096. });
  10097. thread t = thread([&] { svr.listen(HOST, PORT); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. t.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. const std::string req = "GET /check HTTP/1.1\r\n"
  10105. "Host: localhost\r\n"
  10106. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10107. "Connection: close\r\n"
  10108. "\r\n";
  10109. std::string res;
  10110. ASSERT_TRUE(send_request(5, req, &res));
  10111. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10112. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10113. }
  10114. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10115. Server svr;
  10116. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10117. res.set_header("Cache-Control", "no-cache");
  10118. res.set_chunked_content_provider(
  10119. "text/event-stream", [](size_t offset, DataSink &sink) {
  10120. std::string s = "data:";
  10121. s += std::to_string(offset);
  10122. s += "\n\n";
  10123. auto ret = sink.write(s.data(), s.size());
  10124. EXPECT_TRUE(ret);
  10125. std::this_thread::sleep_for(std::chrono::seconds(1));
  10126. return true;
  10127. });
  10128. });
  10129. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10130. svr.wait_until_ready();
  10131. Client client(HOST, PORT);
  10132. const Headers headers = {{"Accept", "text/event-stream"}};
  10133. auto get_thread = std::thread([&client, &headers]() {
  10134. auto res = client.Get(
  10135. "/events", headers,
  10136. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10137. });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. get_thread.join();
  10141. listen_thread.join();
  10142. ASSERT_FALSE(svr.is_running());
  10143. });
  10144. // Give GET time to get a few messages.
  10145. std::this_thread::sleep_for(std::chrono::seconds(2));
  10146. }
  10147. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10148. httplib::Server svr;
  10149. svr.Post("/hi",
  10150. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10151. res.status = StatusCode::OK_200;
  10152. });
  10153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10154. svr.wait_until_ready();
  10155. Client cli(HOST, PORT);
  10156. auto res = cli.Post("/hi", "data", "text/plain");
  10157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10158. EXPECT_EQ(StatusCode::OK_200, res->status);
  10159. svr.stop();
  10160. thread.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. res = cli.Post("/hi", "data", "text/plain");
  10163. ASSERT_FALSE(res);
  10164. }
  10165. TEST(ServerStopTest, ListenFailure) {
  10166. Server svr;
  10167. auto t = thread([&]() {
  10168. auto ret = svr.listen("????", PORT);
  10169. EXPECT_FALSE(ret);
  10170. });
  10171. svr.wait_until_ready();
  10172. svr.stop();
  10173. t.join();
  10174. }
  10175. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10176. TEST(ServerStopTest, Decommision) {
  10177. Server svr;
  10178. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10179. for (int i = 0; i < 4; i++) {
  10180. auto is_even = !(i % 2);
  10181. std::thread t{[&] {
  10182. try {
  10183. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10184. if (is_even) {
  10185. throw std::runtime_error("Some thing that happens to go wrong.");
  10186. }
  10187. svr.listen(HOST, PORT);
  10188. } catch (...) { svr.decommission(); }
  10189. }};
  10190. svr.wait_until_ready();
  10191. // Server is up
  10192. {
  10193. Client cli(HOST, PORT);
  10194. auto res = cli.Get("/hi");
  10195. if (is_even) {
  10196. EXPECT_FALSE(res);
  10197. } else {
  10198. EXPECT_TRUE(res);
  10199. EXPECT_EQ("hi...", res->body);
  10200. }
  10201. }
  10202. svr.stop();
  10203. t.join();
  10204. // Server is down...
  10205. {
  10206. Client cli(HOST, PORT);
  10207. auto res = cli.Get("/hi");
  10208. EXPECT_FALSE(res);
  10209. }
  10210. }
  10211. }
  10212. #endif
  10213. // Helper function for string body upload progress tests
  10214. template <typename SetupHandler, typename ClientCall>
  10215. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10216. ClientCall &&client_call,
  10217. const string &body) {
  10218. Server svr;
  10219. setup_handler(svr);
  10220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. t.join();
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, PORT);
  10227. vector<uint64_t> progress_values;
  10228. bool progress_called = false;
  10229. auto res =
  10230. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10231. progress_values.push_back(current);
  10232. progress_called = true;
  10233. return true;
  10234. });
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. EXPECT_EQ(200, res->status);
  10237. EXPECT_TRUE(progress_called);
  10238. }
  10239. TEST(UploadProgressTest, PostStringBodyBasic) {
  10240. TestStringBodyUploadProgress(
  10241. [](Server &svr) {
  10242. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10243. res.set_content("received", "text/plain");
  10244. });
  10245. },
  10246. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10247. return cli.Post("/test", body, "text/plain", progress_callback);
  10248. },
  10249. "test data for upload progress");
  10250. }
  10251. TEST(UploadProgressTest, PutStringBodyBasic) {
  10252. TestStringBodyUploadProgress(
  10253. [](Server &svr) {
  10254. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10255. res.set_content("put received", "text/plain");
  10256. });
  10257. },
  10258. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10259. return cli.Put("/test", body, "text/plain", progress_callback);
  10260. },
  10261. "put test data for upload progress");
  10262. }
  10263. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("patch received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Patch("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "patch test data for upload progress");
  10274. }
  10275. // Helper function for content provider upload progress tests
  10276. template <typename SetupHandler, typename ClientCall>
  10277. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10278. ClientCall &&client_call) {
  10279. Server svr;
  10280. setup_handler(svr);
  10281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. });
  10286. svr.wait_until_ready();
  10287. Client cli(HOST, PORT);
  10288. vector<uint64_t> progress_values;
  10289. auto res =
  10290. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10291. progress_values.push_back(current);
  10292. return true;
  10293. });
  10294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10295. EXPECT_EQ(200, res->status);
  10296. EXPECT_FALSE(progress_values.empty());
  10297. }
  10298. TEST(UploadProgressTest, PostContentProviderProgress) {
  10299. TestContentProviderUploadProgress(
  10300. [](Server &svr) {
  10301. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10302. res.set_content("provider received", "text/plain");
  10303. });
  10304. },
  10305. [](Client &cli, UploadProgress progress_callback) {
  10306. return cli.Post(
  10307. "/test", 9,
  10308. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10309. sink.os << "test data";
  10310. return true;
  10311. },
  10312. "text/plain", progress_callback);
  10313. });
  10314. }
  10315. // Helper function for multipart upload progress tests
  10316. template <typename SetupHandler, typename ClientCall>
  10317. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10318. ClientCall &&client_call,
  10319. const string &endpoint) {
  10320. Server svr;
  10321. setup_handler(svr);
  10322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. t.join();
  10326. });
  10327. svr.wait_until_ready();
  10328. Client cli(HOST, PORT);
  10329. vector<uint64_t> progress_values;
  10330. UploadFormDataItems items = {
  10331. {"field1", "value1", "", ""},
  10332. {"field2", "longer value for progress tracking test", "", ""},
  10333. {"file1", "file content data for upload progress", "test.txt",
  10334. "text/plain"}};
  10335. auto res = client_call(cli, endpoint, items,
  10336. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10337. progress_values.push_back(current);
  10338. return true;
  10339. });
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(200, res->status);
  10342. EXPECT_FALSE(progress_values.empty());
  10343. }
  10344. TEST(UploadProgressTest, PostMultipartProgress) {
  10345. TestMultipartUploadProgress(
  10346. [](Server &svr) {
  10347. svr.Post("/multipart", [](const Request &req, Response &res) {
  10348. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10349. res.set_content("multipart received", "text/plain");
  10350. });
  10351. },
  10352. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10353. UploadProgress progress_callback) {
  10354. return cli.Post(endpoint, items, progress_callback);
  10355. },
  10356. "/multipart");
  10357. }
  10358. // Helper function for basic download progress tests
  10359. template <typename SetupHandler, typename ClientCall>
  10360. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10361. ClientCall &&client_call, const string &endpoint,
  10362. size_t expected_content_size) {
  10363. Server svr;
  10364. setup_handler(svr);
  10365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. t.join();
  10369. });
  10370. svr.wait_until_ready();
  10371. Client cli(HOST, PORT);
  10372. vector<uint64_t> progress_values;
  10373. auto res = client_call(cli, endpoint,
  10374. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10375. progress_values.push_back(current);
  10376. return true;
  10377. });
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. EXPECT_EQ(200, res->status);
  10380. EXPECT_FALSE(progress_values.empty());
  10381. EXPECT_EQ(expected_content_size, res->body.size());
  10382. }
  10383. TEST(DownloadProgressTest, GetBasic) {
  10384. TestBasicDownloadProgress(
  10385. [](Server &svr) {
  10386. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10387. string content(1000, 'D');
  10388. res.set_content(content, "text/plain");
  10389. });
  10390. },
  10391. [](Client &cli, const string &endpoint,
  10392. DownloadProgress progress_callback) {
  10393. return cli.Get(endpoint, progress_callback);
  10394. },
  10395. "/download", 1000u);
  10396. }
  10397. // Helper function for content receiver download progress tests
  10398. template <typename SetupHandler, typename ClientCall>
  10399. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10400. ClientCall &&client_call,
  10401. const string &endpoint,
  10402. size_t expected_content_size) {
  10403. Server svr;
  10404. setup_handler(svr);
  10405. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10406. auto se = detail::scope_exit([&] {
  10407. svr.stop();
  10408. t.join();
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, PORT);
  10412. vector<uint64_t> progress_values;
  10413. string received_body;
  10414. auto res = client_call(
  10415. cli, endpoint,
  10416. [&](const char *data, size_t data_length) -> bool {
  10417. received_body.append(data, data_length);
  10418. return true;
  10419. },
  10420. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10421. progress_values.push_back(current);
  10422. return true;
  10423. });
  10424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10425. EXPECT_EQ(200, res->status);
  10426. EXPECT_FALSE(progress_values.empty());
  10427. EXPECT_EQ(expected_content_size, received_body.size());
  10428. EXPECT_TRUE(res->body.empty());
  10429. }
  10430. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10431. TestContentReceiverDownloadProgress(
  10432. [](Server &svr) {
  10433. svr.Get("/download-receiver",
  10434. [](const Request & /*req*/, Response &res) {
  10435. string content(2000, 'R');
  10436. res.set_content(content, "text/plain");
  10437. });
  10438. },
  10439. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10440. DownloadProgress progress_callback) {
  10441. return cli.Get(endpoint, content_receiver, progress_callback);
  10442. },
  10443. "/download-receiver", 2000u);
  10444. }
  10445. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10446. // A provider reaching a pass with nothing to hand over - an empty buffer
  10447. // popped off a queue, say - must not be taken to mean the body is finished.
  10448. // It used to end the loop with the terminating chunk unwritten while the
  10449. // server still considered the response complete, so the peer waited for an
  10450. // end that never arrived.
  10451. Server svr;
  10452. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10453. auto step = std::make_shared<int>(0);
  10454. res.set_chunked_content_provider("text/plain",
  10455. [step](size_t /*offset*/, DataSink &sink) {
  10456. switch ((*step)++) {
  10457. case 0: sink.write("", 0); break;
  10458. case 1: sink.write("hello", 5); break;
  10459. default: sink.done(); break;
  10460. }
  10461. return true;
  10462. });
  10463. });
  10464. auto port = svr.bind_to_any_port(HOST);
  10465. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10466. auto listen_se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. listen_thread.join();
  10469. ASSERT_FALSE(svr.is_running());
  10470. });
  10471. svr.wait_until_ready();
  10472. Client cli(HOST, port);
  10473. // Without the fix the body is never terminated, so bound the wait rather
  10474. // than letting the test hang on the default read timeout.
  10475. cli.set_read_timeout(5, 0);
  10476. auto res = cli.Get("/stream");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. EXPECT_EQ("hello", res->body);
  10480. }
  10481. TEST(StreamingTest, NoContentLengthStreaming) {
  10482. Server svr;
  10483. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10484. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10485. if (offset < 6) {
  10486. sink.os << (offset < 3 ? "a" : "b");
  10487. } else {
  10488. sink.done();
  10489. }
  10490. return true;
  10491. });
  10492. });
  10493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10494. auto listen_se = detail::scope_exit([&] {
  10495. svr.stop();
  10496. listen_thread.join();
  10497. ASSERT_FALSE(svr.is_running());
  10498. });
  10499. svr.wait_until_ready();
  10500. Client client(HOST, PORT);
  10501. auto get_thread = std::thread([&client]() {
  10502. std::string s;
  10503. auto res =
  10504. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10505. s += std::string(data, len);
  10506. return true;
  10507. });
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. EXPECT_EQ("aaabbb", s);
  10511. });
  10512. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10513. // Give GET time to get a few messages.
  10514. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10515. }
  10516. TEST(MountTest, Unmount) {
  10517. Server svr;
  10518. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10519. auto se = detail::scope_exit([&] {
  10520. svr.stop();
  10521. listen_thread.join();
  10522. ASSERT_FALSE(svr.is_running());
  10523. });
  10524. svr.wait_until_ready();
  10525. Client cli("localhost", PORT);
  10526. svr.set_mount_point("/mount2", "./www2");
  10527. auto res = cli.Get("/");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. res = cli.Get("/mount2/dir/test.html");
  10531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10532. EXPECT_EQ(StatusCode::OK_200, res->status);
  10533. svr.set_mount_point("/", "./www");
  10534. res = cli.Get("/dir/");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::OK_200, res->status);
  10537. svr.remove_mount_point("/");
  10538. res = cli.Get("/dir/");
  10539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10541. svr.remove_mount_point("/mount2");
  10542. res = cli.Get("/mount2/dir/test.html");
  10543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10545. }
  10546. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10547. Server svr;
  10548. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10549. svr.Get("/api/hello", [](const Request &, Response &res) {
  10550. res.set_content("api", "text/plain");
  10551. });
  10552. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. listen_thread.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. });
  10558. svr.wait_until_ready();
  10559. Client cli(HOST, PORT);
  10560. auto res = cli.Get("/dir/test.html");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. res = cli.Get("/api/hello");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::OK_200, res->status);
  10566. EXPECT_EQ("api", res->body);
  10567. }
  10568. TEST(MountTest, PathSegmentBoundary) {
  10569. Server svr;
  10570. svr.set_mount_point("/mount2", "./www2");
  10571. svr.set_mount_point("/", "./www");
  10572. auto port = svr.bind_to_any_port(HOST);
  10573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10574. auto se = detail::scope_exit([&] {
  10575. svr.stop();
  10576. listen_thread.join();
  10577. ASSERT_FALSE(svr.is_running());
  10578. });
  10579. svr.wait_until_ready();
  10580. Client cli(HOST, port);
  10581. auto res = cli.Get("/mount2/dir/test.html");
  10582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10583. EXPECT_EQ(StatusCode::OK_200, res->status);
  10584. // "/mount2" must not match part-way through a path segment.
  10585. res = cli.Get("/mount2dir/test.html");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10588. // A mount point ending in '/' keeps matching every path below it.
  10589. res = cli.Get("/dir/test.html");
  10590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10591. EXPECT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. TEST(MountTest, Redicect) {
  10594. Server svr;
  10595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. listen_thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.set_mount_point("/", "./www");
  10602. svr.wait_until_ready();
  10603. Client cli("localhost", PORT);
  10604. auto res = cli.Get("/dir/");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_EQ(StatusCode::OK_200, res->status);
  10607. res = cli.Get("/dir");
  10608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10609. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10610. res = cli.Get("/file");
  10611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10612. EXPECT_EQ(StatusCode::OK_200, res->status);
  10613. res = cli.Get("/file/");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10616. cli.set_follow_location(true);
  10617. res = cli.Get("/dir");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(StatusCode::OK_200, res->status);
  10620. }
  10621. TEST(MountTest, MultibytesPathName) {
  10622. Server svr;
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.set_mount_point("/", "./www");
  10630. svr.wait_until_ready();
  10631. Client cli("localhost", PORT);
  10632. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10634. EXPECT_EQ(StatusCode::OK_200, res->status);
  10635. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10636. }
  10637. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10638. // in the pre-routing handler sees the path of every file that is served
  10639. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10640. Server svr;
  10641. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10642. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10643. if (req.path == "/dir/test.html") {
  10644. res.status = StatusCode::Unauthorized_401;
  10645. return Server::HandlerResponse::Handled;
  10646. }
  10647. return Server::HandlerResponse::Unhandled;
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. ASSERT_LT(0, port);
  10651. thread t = thread([&] { svr.listen_after_bind(); });
  10652. auto se = detail::scope_exit([&] {
  10653. svr.stop();
  10654. t.join();
  10655. ASSERT_FALSE(svr.is_running());
  10656. });
  10657. svr.wait_until_ready();
  10658. Client cli(HOST, port);
  10659. for (auto path :
  10660. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10661. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10662. SCOPED_TRACE(path);
  10663. auto res = cli.Get(path);
  10664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10665. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10666. }
  10667. }
  10668. #ifdef _WIN32
  10669. // Issue #2435: mmap::open() must succeed even when another handle holds
  10670. // the file open for writing (e.g. an active log file).
  10671. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10672. const char *path = "mmap_concurrent_writer_test.txt";
  10673. const char *content = "hello";
  10674. {
  10675. std::ofstream f(path, std::ios::binary);
  10676. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10677. }
  10678. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10679. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10680. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10681. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10682. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10683. detail::mmap m(path);
  10684. ASSERT_TRUE(m.is_open());
  10685. EXPECT_EQ(strlen(content), m.size());
  10686. char buf[8];
  10687. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10688. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10689. }
  10690. #endif
  10691. #ifndef _WIN32
  10692. // A directory or a device has no size to serve.
  10693. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10694. const char *path = "./mmap_not_regular_test_dir";
  10695. ASSERT_EQ(0, ::mkdir(path, 0755));
  10696. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10697. for (auto p : {path, "/dev/null"}) {
  10698. detail::mmap m(p);
  10699. EXPECT_FALSE(m.is_open()) << p;
  10700. EXPECT_EQ(0U, m.size()) << p;
  10701. }
  10702. Server svr;
  10703. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10704. res.set_file_content("/dev/null");
  10705. });
  10706. auto port = svr.bind_to_any_port(HOST);
  10707. thread t = thread([&] { svr.listen_after_bind(); });
  10708. auto se = detail::scope_exit([&] {
  10709. svr.stop();
  10710. t.join();
  10711. });
  10712. svr.wait_until_ready();
  10713. auto res = Client(HOST, port).Get("/null");
  10714. ASSERT_TRUE(res);
  10715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10716. }
  10717. #endif
  10718. #ifdef __linux__
  10719. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10720. TEST(MmapTest, FileIsNotMapped) {
  10721. const char *path = "mmap_not_mapped_test.txt";
  10722. {
  10723. std::ofstream f(path, std::ios::binary);
  10724. f << "hello";
  10725. }
  10726. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10727. detail::mmap m(path);
  10728. ASSERT_TRUE(m.is_open());
  10729. std::ifstream maps("/proc/self/maps");
  10730. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10731. std::istreambuf_iterator<char>());
  10732. EXPECT_EQ(std::string::npos, mappings.find(path));
  10733. }
  10734. #endif
  10735. TEST(KeepAliveTest, ReadTimeout) {
  10736. Server svr;
  10737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10738. std::this_thread::sleep_for(std::chrono::seconds(2));
  10739. res.set_content("a", "text/plain");
  10740. });
  10741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10742. res.set_content("b", "text/plain");
  10743. });
  10744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli("localhost", PORT);
  10752. cli.set_keep_alive(true);
  10753. cli.set_read_timeout(std::chrono::seconds(1));
  10754. auto resa = cli.Get("/a");
  10755. ASSERT_FALSE(resa);
  10756. EXPECT_EQ(Error::Read, resa.error());
  10757. auto resb = cli.Get("/b");
  10758. ASSERT_TRUE(resb);
  10759. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10760. EXPECT_EQ("b", resb->body);
  10761. }
  10762. TEST(KeepAliveTest, MaxCount) {
  10763. size_t keep_alive_max_count = 3;
  10764. Server svr;
  10765. svr.set_keep_alive_max_count(keep_alive_max_count);
  10766. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10767. res.set_content("Hello World!", "text/plain");
  10768. });
  10769. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10770. auto se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli(HOST, PORT);
  10777. cli.set_keep_alive(true);
  10778. for (size_t i = 0; i < 5; i++) {
  10779. auto result = cli.Get("/hi");
  10780. ASSERT_TRUE(result);
  10781. EXPECT_EQ(StatusCode::OK_200, result->status);
  10782. if (i == keep_alive_max_count - 1) {
  10783. EXPECT_EQ("close", result->get_header_value("Connection"));
  10784. } else {
  10785. EXPECT_FALSE(result->has_header("Connection"));
  10786. }
  10787. }
  10788. }
  10789. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10790. // can pull the next one into the server's buffer. The server must serve it
  10791. // without waiting for the socket to become readable again. The keep-alive
  10792. // timeout outlasts the client's read timeout, so a request left waiting for it
  10793. // shows up as a missing response.
  10794. static void serve_pipelining_routes(Server &svr,
  10795. const std::function<void(int)> &client) {
  10796. svr.set_keep_alive_timeout(5);
  10797. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10798. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10799. });
  10800. svr.Post("/echo", [](const Request &req, Response &res) {
  10801. res.set_content("echo " + req.body, "text/plain");
  10802. });
  10803. auto port = svr.bind_to_any_port(HOST);
  10804. thread t = thread([&] { svr.listen_after_bind(); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. t.join();
  10808. });
  10809. svr.wait_until_ready();
  10810. client(port);
  10811. }
  10812. static std::string
  10813. send_pipelined_requests(const std::vector<std::string> &parts) {
  10814. Server svr;
  10815. std::string res;
  10816. serve_pipelining_routes(svr, [&](int port) {
  10817. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10818. });
  10819. return res;
  10820. }
  10821. static void expect_in_order(const std::string &res,
  10822. const std::vector<std::string> &bodies) {
  10823. size_t pos = 0;
  10824. for (const auto &body : bodies) {
  10825. pos = res.find(body, pos);
  10826. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10827. pos += body.size();
  10828. }
  10829. }
  10830. TEST(KeepAliveTest, PipelinedRequests) {
  10831. auto res = send_pipelined_requests(
  10832. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10833. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10834. "Content-Length: 4\r\n\r\nbody"
  10835. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10836. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10837. }
  10838. // The second request starts in the server's buffer and ends on the socket.
  10839. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10840. auto res =
  10841. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10842. "GET /hi/2 HTTP/1.1\r\nHo",
  10843. "st: localhost\r\nConnection: close\r\n\r\n"});
  10844. expect_in_order(res, {"hi 1", "hi 2"});
  10845. }
  10846. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10847. // CRLF after a body does not turn into a 400 for the next request.
  10848. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10849. auto res = send_pipelined_requests(
  10850. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10851. "Content-Length: 4\r\n\r\nbody\r\n"
  10852. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10853. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10854. expect_in_order(res, {"echo body", "hi 2"});
  10855. }
  10856. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10857. // must not be served as the next request.
  10858. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10859. auto res = send_pipelined_requests(
  10860. {"INVALID REQUEST LINE\r\n\r\n"
  10861. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10862. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10863. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10864. }
  10865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10866. // Over TLS, the next request is held by the TLS library as already decrypted
  10867. // data rather than on the socket.
  10868. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. std::string res;
  10871. serve_pipelining_routes(svr, [&](int port) {
  10872. // One part, so all three requests arrive in one TLS record
  10873. EXPECT_TRUE(send_ssl_request_in_parts(
  10874. 2,
  10875. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10877. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10878. &res, port));
  10879. });
  10880. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10881. }
  10882. #endif
  10883. TEST(KeepAliveTest, Issue1041) {
  10884. Server svr;
  10885. svr.set_keep_alive_timeout(3);
  10886. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10887. res.set_content("Hello World!", "text/plain");
  10888. });
  10889. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10890. auto se = detail::scope_exit([&] {
  10891. svr.stop();
  10892. listen_thread.join();
  10893. ASSERT_FALSE(svr.is_running());
  10894. });
  10895. svr.wait_until_ready();
  10896. Client cli(HOST, PORT);
  10897. cli.set_keep_alive(true);
  10898. auto result = cli.Get("/hi");
  10899. ASSERT_TRUE(result);
  10900. EXPECT_EQ(StatusCode::OK_200, result->status);
  10901. std::this_thread::sleep_for(std::chrono::seconds(5));
  10902. result = cli.Get("/hi");
  10903. ASSERT_TRUE(result);
  10904. EXPECT_EQ(StatusCode::OK_200, result->status);
  10905. }
  10906. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10907. Server svr;
  10908. svr.set_keep_alive_max_count(0);
  10909. std::set<int> remote_ports;
  10910. svr.Get("/hi", [&](const Request &req, Response &res) {
  10911. remote_ports.insert(req.remote_port);
  10912. res.set_content("hi", "text/plain");
  10913. });
  10914. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10915. auto se = detail::scope_exit([&] {
  10916. svr.stop();
  10917. listen_thread.join();
  10918. ASSERT_FALSE(svr.is_running());
  10919. });
  10920. svr.wait_until_ready();
  10921. Client cli(HOST, PORT);
  10922. cli.set_keep_alive(true);
  10923. for (int i = 0; i < 3; i++) {
  10924. auto res = cli.Get("/hi");
  10925. ASSERT_TRUE(res);
  10926. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10927. }
  10928. // All three over one connection
  10929. EXPECT_EQ(1u, remote_ports.size());
  10930. }
  10931. TEST(KeepAliveTest, Issue1959) {
  10932. Server svr;
  10933. svr.set_keep_alive_timeout(5);
  10934. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10935. res.set_content("a", "text/plain");
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. if (!svr.is_running()) return;
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli("localhost", PORT);
  10946. cli.set_keep_alive(true);
  10947. using namespace std::chrono;
  10948. auto start = steady_clock::now();
  10949. cli.Get("/a");
  10950. svr.stop();
  10951. listen_thread.join();
  10952. auto end = steady_clock::now();
  10953. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10954. EXPECT_LT(elapsed, 5000);
  10955. }
  10956. #ifdef CPPHTTPLIB_SSL_ENABLED
  10957. TEST(KeepAliveTest, SSLClientReconnection) {
  10958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10959. ASSERT_TRUE(svr.is_valid());
  10960. svr.set_keep_alive_timeout(1);
  10961. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10962. res.set_content("Hello World!", "text/plain");
  10963. });
  10964. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. SSLClient cli(HOST, PORT);
  10972. cli.enable_server_certificate_verification(false);
  10973. cli.set_keep_alive(true);
  10974. auto result = cli.Get("/hi");
  10975. ASSERT_TRUE(result);
  10976. EXPECT_EQ(StatusCode::OK_200, result->status);
  10977. result = cli.Get("/hi");
  10978. ASSERT_TRUE(result);
  10979. EXPECT_EQ(StatusCode::OK_200, result->status);
  10980. std::this_thread::sleep_for(std::chrono::seconds(2));
  10981. // Recoonect
  10982. result = cli.Get("/hi");
  10983. ASSERT_TRUE(result);
  10984. EXPECT_EQ(StatusCode::OK_200, result->status);
  10985. result = cli.Get("/hi");
  10986. ASSERT_TRUE(result);
  10987. EXPECT_EQ(StatusCode::OK_200, result->status);
  10988. }
  10989. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10991. ASSERT_TRUE(svr.is_valid());
  10992. svr.set_keep_alive_timeout(1);
  10993. std::string content = "reconnect";
  10994. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10995. res.set_content("Hello World!", "text/plain");
  10996. });
  10997. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. listen_thread.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. SSLClient cli(HOST, PORT);
  11005. cli.enable_server_certificate_verification(false);
  11006. cli.set_keep_alive(true);
  11007. auto result = cli.Post(
  11008. "/hi", content.size(),
  11009. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11010. sink.write(content.c_str(), content.size());
  11011. return true;
  11012. },
  11013. "text/plain");
  11014. ASSERT_TRUE(result);
  11015. EXPECT_EQ(200, result->status);
  11016. std::this_thread::sleep_for(std::chrono::seconds(2));
  11017. // Recoonect
  11018. result = cli.Post(
  11019. "/hi", content.size(),
  11020. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11021. sink.write(content.c_str(), content.size());
  11022. return true;
  11023. },
  11024. "text/plain");
  11025. ASSERT_TRUE(result);
  11026. EXPECT_EQ(200, result->status);
  11027. result = cli.Post(
  11028. "/hi", content.size(),
  11029. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11030. sink.write(content.c_str(), content.size());
  11031. return true;
  11032. },
  11033. "text/plain");
  11034. ASSERT_TRUE(result);
  11035. EXPECT_EQ(200, result->status);
  11036. }
  11037. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11038. using namespace httplib::tls;
  11039. {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.Get("/sni", [&](const Request &req, Response &res) {
  11043. std::string expected = req.sni();
  11044. EXPECT_EQ(expected, req.get_param_value("expected"));
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. listen_thread.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. {
  11055. SSLClient cli("localhost", PORT);
  11056. cli.enable_server_certificate_verification(false);
  11057. auto res = cli.Get("/sni?expected=localhost");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. }
  11060. {
  11061. SSLClient cli("::1", PORT);
  11062. cli.enable_server_certificate_verification(false);
  11063. auto res = cli.Get("/sni?expected=");
  11064. // NOTE: This may fail if the server is listening on IPv4 only
  11065. // (e.g., when localhost resolves to 127.0.0.1 only)
  11066. if (res) {
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. } else {
  11069. EXPECT_EQ(Error::Connection, res.error());
  11070. }
  11071. }
  11072. }
  11073. }
  11074. // The SNI of a failed handshake does not reach the next connection that the
  11075. // same worker thread serves
  11076. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11078. ASSERT_TRUE(svr.is_valid());
  11079. svr.new_task_queue = [] { return new ThreadPool(1); };
  11080. svr.Get("/sni", [](const Request &req, Response &res) {
  11081. res.set_content(req.sni(), "text/plain");
  11082. });
  11083. auto port = svr.bind_to_any_port("127.0.0.1");
  11084. ASSERT_LT(0, port);
  11085. thread t = thread([&] { svr.listen_after_bind(); });
  11086. auto se = detail::scope_exit([&] {
  11087. svr.stop();
  11088. t.join();
  11089. ASSERT_FALSE(svr.is_running());
  11090. });
  11091. svr.wait_until_ready();
  11092. {
  11093. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11094. SSLClient cli("localhost", port);
  11095. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11096. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11097. auto res = cli.Get("/sni");
  11098. ASSERT_FALSE(res);
  11099. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11100. }
  11101. // An IP host sends no SNI (RFC 6066)
  11102. SSLClient cli("127.0.0.1", port);
  11103. cli.enable_server_certificate_verification(false);
  11104. auto res = cli.Get("/sni");
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. EXPECT_EQ("", res->body);
  11107. }
  11108. #endif
  11109. TEST(ClientProblemDetectionTest, ContentProvider) {
  11110. Server svr;
  11111. size_t content_length = 1024 * 1024;
  11112. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11113. res.set_content_provider(
  11114. content_length, "text/plain",
  11115. [&](size_t offset, size_t length, DataSink &sink) {
  11116. auto out_len = std::min(length, static_cast<size_t>(1024));
  11117. std::string out(out_len, '@');
  11118. sink.write(out.data(), out_len);
  11119. return offset < 4096;
  11120. },
  11121. [](bool success) { ASSERT_FALSE(success); });
  11122. });
  11123. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11124. res.set_content_provider(
  11125. 0, "text/plain",
  11126. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11127. EXPECT_TRUE(false);
  11128. return true;
  11129. },
  11130. [](bool success) { ASSERT_FALSE(success); });
  11131. });
  11132. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11133. auto se = detail::scope_exit([&] {
  11134. svr.stop();
  11135. listen_thread.join();
  11136. ASSERT_FALSE(svr.is_running());
  11137. });
  11138. svr.wait_until_ready();
  11139. Client cli("localhost", PORT);
  11140. {
  11141. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11142. size_t /*data_length*/) { return false; });
  11143. ASSERT_FALSE(res);
  11144. }
  11145. {
  11146. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11147. size_t /*data_length*/) { return false; });
  11148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11149. }
  11150. }
  11151. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11152. // A provider that reports success without writing anything and without
  11153. // calling done() used to be handed the same offset and length again on every
  11154. // pass, so it spun for as long as the peer stayed connected.
  11155. Server svr;
  11156. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11157. res.set_content("ok", "text/plain");
  11158. });
  11159. auto port = svr.bind_to_any_port(HOST);
  11160. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11161. auto se = detail::scope_exit([&] {
  11162. svr.stop();
  11163. listen_thread.join();
  11164. ASSERT_FALSE(svr.is_running());
  11165. });
  11166. svr.wait_until_ready();
  11167. std::atomic<int> call_count{0};
  11168. Client cli(HOST, port);
  11169. auto res = cli.Post(
  11170. "/", 1024,
  11171. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11172. // Give up after enough passes to show the spin, so that losing the
  11173. // check below fails this test instead of hanging it.
  11174. return ++call_count < 100;
  11175. },
  11176. "text/plain");
  11177. ASSERT_FALSE(res);
  11178. EXPECT_EQ(Error::Write, res.error());
  11179. EXPECT_EQ(1, call_count.load());
  11180. }
  11181. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11182. // A writer only has to assign `write`. The other three used to be left as
  11183. // empty std::functions, so a provider calling one threw
  11184. // std::bad_function_call out of the thread running it and took the whole
  11185. // process down.
  11186. DataSink sink;
  11187. std::string written;
  11188. sink.write = [&](const char *data, size_t data_len) {
  11189. written.append(data, data_len);
  11190. return true;
  11191. };
  11192. EXPECT_TRUE(sink.is_writable());
  11193. sink.done();
  11194. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11195. EXPECT_TRUE(written.empty());
  11196. }
  11197. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11198. // A sink that cannot carry trailers still has to finish.
  11199. DataSink sink;
  11200. auto done_count = 0;
  11201. sink.done = [&]() { done_count++; };
  11202. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11203. EXPECT_EQ(1, done_count);
  11204. }
  11205. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11206. Server svr;
  11207. const std::string body(4096, 'x');
  11208. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11209. res.set_content_provider(body.size(), "text/plain",
  11210. [&](size_t offset, size_t length, DataSink &sink) {
  11211. sink.write(body.data() + offset, length);
  11212. sink.done();
  11213. return true;
  11214. });
  11215. });
  11216. auto port = svr.bind_to_any_port(HOST);
  11217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. listen_thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. Client cli(HOST, port);
  11225. auto res = cli.Get("/");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::OK_200, res->status);
  11228. EXPECT_EQ(body, res->body);
  11229. }
  11230. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11231. Server svr;
  11232. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(
  11234. 1024, "text/plain",
  11235. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11236. sink.write("hello", 5);
  11237. sink.done(); // short of the 1024 bytes the response promised
  11238. return true;
  11239. });
  11240. });
  11241. auto port = svr.bind_to_any_port(HOST);
  11242. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11243. auto se = detail::scope_exit([&] {
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. Client cli(HOST, port);
  11250. cli.set_read_timeout(5, 0);
  11251. // The response is short of its Content-Length, so the client cannot read a
  11252. // complete body. What matters is that this returns at all: a no-op done()
  11253. // would leave the writer looping over a provider that never makes progress.
  11254. auto res = cli.Get("/");
  11255. EXPECT_FALSE(res);
  11256. }
  11257. // Read as the next response by a peer that sees it after a framed body.
  11258. static const std::string smuggled_response =
  11259. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11260. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11261. Server svr;
  11262. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11263. res.set_content_provider(
  11264. 5, "text/plain",
  11265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11266. auto data = "AAAAA" + smuggled_response;
  11267. sink.write(data.data(), data.size());
  11268. return true;
  11269. });
  11270. });
  11271. thread t = thread([&] { svr.listen(HOST, PORT); });
  11272. auto se = detail::scope_exit([&] {
  11273. svr.stop();
  11274. t.join();
  11275. ASSERT_FALSE(svr.is_running());
  11276. });
  11277. svr.wait_until_ready();
  11278. std::string resp;
  11279. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11280. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11281. resp.clear();
  11282. ASSERT_TRUE(send_request(
  11283. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11284. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11285. }
  11286. TEST(NoContentTest, BodyIsNotSent) {
  11287. Server svr;
  11288. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11289. res.status = StatusCode::NoContent_204;
  11290. res.set_content(smuggled_response, "text/plain");
  11291. });
  11292. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11293. res.status = StatusCode::NotModified_304;
  11294. res.set_chunked_content_provider(
  11295. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11296. sink.write(smuggled_response.data(), smuggled_response.size());
  11297. sink.done();
  11298. return true;
  11299. });
  11300. });
  11301. thread t = thread([&] { svr.listen(HOST, PORT); });
  11302. auto se = detail::scope_exit([&] {
  11303. svr.stop();
  11304. t.join();
  11305. ASSERT_FALSE(svr.is_running());
  11306. });
  11307. svr.wait_until_ready();
  11308. for (auto path : {"/204", "/304"}) {
  11309. std::string resp;
  11310. ASSERT_TRUE(send_request(
  11311. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11312. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11313. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11314. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11315. }
  11316. }
  11317. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11318. Server svr;
  11319. std::atomic<bool> smuggled(false);
  11320. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11321. res.set_content("ok", "text/plain");
  11322. });
  11323. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11324. smuggled = true;
  11325. });
  11326. auto port = svr.bind_to_any_port(HOST);
  11327. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. listen_thread.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. });
  11333. svr.wait_until_ready();
  11334. // What follows the body would be read as the next request.
  11335. Client cli(HOST, port);
  11336. auto res = cli.Post(
  11337. "/", 5,
  11338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11339. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11340. sink.write(data.data(), data.size());
  11341. return true;
  11342. },
  11343. "text/plain");
  11344. ASSERT_FALSE(res);
  11345. EXPECT_EQ(Error::Write, res.error());
  11346. EXPECT_FALSE(smuggled);
  11347. }
  11348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11349. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11350. // The compressed path builds the whole body before connecting, so this
  11351. // fails client-side and never reaches a server.
  11352. Client cli(HOST, PORT);
  11353. cli.set_compress(true);
  11354. auto res = cli.Post(
  11355. "/", 1024,
  11356. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11357. sink.write("hello", 5);
  11358. sink.done(); // short of the 1024 bytes the request announced
  11359. return true;
  11360. },
  11361. "text/plain");
  11362. ASSERT_FALSE(res);
  11363. EXPECT_EQ(Error::Write, res.error());
  11364. }
  11365. #endif
  11366. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11367. Server svr;
  11368. svr.set_error_handler([](Request const &, Response &res) -> void {
  11369. res.set_chunked_content_provider(
  11370. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11371. sink.os << "hello";
  11372. sink.os << "world";
  11373. sink.done();
  11374. return true;
  11375. });
  11376. });
  11377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. Client cli("localhost", PORT);
  11385. auto res = cli.Get("/");
  11386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11388. EXPECT_EQ("helloworld", res->body);
  11389. }
  11390. // A body set after a content provider must replace it, not be sent through it.
  11391. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11392. Server svr;
  11393. svr.set_mount_point("/", "./www");
  11394. svr.set_file_request_handler([](const Request &req, Response &res) {
  11395. if (req.path == "/dir/test.html") {
  11396. res.status = StatusCode::Forbidden_403;
  11397. res.set_content(std::string(5000, 'D'), "text/plain");
  11398. } else if (req.path == "/file") {
  11399. res.status = StatusCode::Forbidden_403;
  11400. res.body = "Denied";
  11401. }
  11402. });
  11403. auto port = svr.bind_to_any_port(HOST);
  11404. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11405. auto se = detail::scope_exit([&] {
  11406. svr.stop();
  11407. t.join();
  11408. ASSERT_FALSE(svr.is_running());
  11409. });
  11410. svr.wait_until_ready();
  11411. Client cli(HOST, port);
  11412. {
  11413. auto res = cli.Get("/dir/test.html");
  11414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11415. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11416. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11417. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11418. }
  11419. {
  11420. auto res = cli.Get("/file");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11423. EXPECT_EQ("Denied", res->body);
  11424. }
  11425. {
  11426. auto res = cli.Get("/dir/index.html");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. EXPECT_EQ(0U, res->body.find("<html>"));
  11430. }
  11431. }
  11432. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11433. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11434. Server svr;
  11435. std::vector<bool> released;
  11436. std::mutex released_mutex;
  11437. auto releaser = [&](bool success) {
  11438. std::lock_guard<std::mutex> guard(released_mutex);
  11439. released.push_back(success);
  11440. };
  11441. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11442. return sink.write(&"hello"[offset], length);
  11443. };
  11444. svr.Get("/sized", [&](const Request &, Response &res) {
  11445. res.status = StatusCode::NotFound_404;
  11446. res.set_content_provider(5, "text/plain", provider, releaser);
  11447. });
  11448. svr.Get("/chunked", [&](const Request &, Response &res) {
  11449. res.status = StatusCode::ServiceUnavailable_503;
  11450. res.set_chunked_content_provider(
  11451. "text/plain",
  11452. [](size_t, DataSink &sink) {
  11453. sink.os << "chunk";
  11454. sink.done();
  11455. return true;
  11456. },
  11457. releaser);
  11458. });
  11459. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11460. res.set_content_provider(5, "text/plain", provider, releaser);
  11461. throw std::runtime_error("after the provider");
  11462. });
  11463. svr.set_error_handler([](const Request &req, Response &res) {
  11464. // Leave the exception handler's content to it.
  11465. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11466. res.set_content(std::string(1000, 'E'), "text/html");
  11467. return Server::HandlerResponse::Handled;
  11468. });
  11469. svr.set_exception_handler(
  11470. [](const Request &, Response &res, std::exception_ptr) {
  11471. res.status = StatusCode::InternalServerError_500;
  11472. res.set_content(std::string(1000, 'X'), "text/html");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli(HOST, port);
  11483. {
  11484. auto res = cli.Get("/sized");
  11485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11487. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11488. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11489. }
  11490. {
  11491. auto res = cli.Get("/chunked");
  11492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11493. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11494. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11495. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11496. }
  11497. {
  11498. auto res = cli.Get("/throw");
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11501. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11502. }
  11503. std::lock_guard<std::mutex> guard(released_mutex);
  11504. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11505. }
  11506. #endif
  11507. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11508. Server svr;
  11509. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11510. return sink.write(&"abc"[offset], length);
  11511. };
  11512. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11513. res.set_file_content("./www/dir/test.html");
  11514. res.set_content("body", "text/plain");
  11515. });
  11516. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11517. res.set_content(std::string(100, 'B'), "text/plain");
  11518. res.set_file_content("./www/dir/test.html");
  11519. });
  11520. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11521. res.set_content(std::string(100, 'B'), "text/plain");
  11522. res.set_content_provider(3, "text/x-provider", abc);
  11523. });
  11524. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11525. res.set_content_provider(3, "text/x-provider", abc);
  11526. res.set_content(std::string(100, 'B'), "text/plain");
  11527. });
  11528. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11529. res.set_content_provider(3, "text/x-provider", abc);
  11530. res.set_file_content("./www/dir/test.html", "text/x-file");
  11531. });
  11532. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11533. res.set_file_content("./www/dir/test.html");
  11534. res.set_header("Content-Type", "text/x-handler");
  11535. });
  11536. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11537. res.set_content_provider(3, "text/plain", abc);
  11538. res.body = "direct";
  11539. });
  11540. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11541. res.set_file_content("./www/dir/test.html");
  11542. res.body = "direct";
  11543. });
  11544. auto port = svr.bind_to_any_port(HOST);
  11545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11546. auto se = detail::scope_exit([&] {
  11547. svr.stop();
  11548. t.join();
  11549. ASSERT_FALSE(svr.is_running());
  11550. });
  11551. svr.wait_until_ready();
  11552. Client cli(HOST, port);
  11553. auto expect_body = [&](const char *path, const std::string &body,
  11554. const std::string &type) {
  11555. // Uncompressed, so Content-Length can be compared with the body.
  11556. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11557. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11558. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11559. EXPECT_EQ(body, res->body) << path;
  11560. EXPECT_EQ(std::to_string(body.size()),
  11561. res->get_header_value("Content-Length"))
  11562. << path;
  11563. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11564. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11565. };
  11566. expect_body("/file-then-body", "body", "text/plain");
  11567. expect_body("/body-then-file", "test.html", "text/html");
  11568. expect_body("/body-then-provider", "abc", "text/x-provider");
  11569. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11570. expect_body("/provider-then-file", "test.html", "text/x-file");
  11571. expect_body("/file-then-header", "test.html", "text/x-handler");
  11572. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11573. expect_body("/file-then-direct-body", "direct", "text/plain");
  11574. // Ranges are checked against the body, not the dropped provider.
  11575. {
  11576. auto res = cli.Get("/provider-then-direct-body",
  11577. Headers{{make_range_header({{1, 2}})}});
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11580. EXPECT_EQ("ir", res->body);
  11581. }
  11582. {
  11583. auto res = cli.Get("/file-then-direct-body",
  11584. Headers{{make_range_header({{7, 8}})}});
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11587. }
  11588. }
  11589. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11590. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11591. const char *path = "./truncated_while_served.txt";
  11592. const size_t size = 32 * 1024 * 1024;
  11593. {
  11594. std::ofstream f(path, std::ios::binary);
  11595. f << std::string(size, 'x');
  11596. }
  11597. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11598. // Over TLS, where the bytes are encrypted in this process rather than
  11599. // copied by send().
  11600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11601. svr.Get("/file", [&](const Request &, Response &res) {
  11602. res.set_file_content(path, "text/plain");
  11603. });
  11604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. thread.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. });
  11610. svr.wait_until_ready();
  11611. // The file shrinks once the first bytes are in, as a rewrite in place
  11612. // would, and reading the mapping past its new end used to raise SIGBUS.
  11613. SSLClient cli(HOST, PORT);
  11614. cli.enable_server_certificate_verification(false);
  11615. size_t received = 0;
  11616. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11617. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11618. received += len;
  11619. return true;
  11620. });
  11621. EXPECT_FALSE(res);
  11622. EXPECT_LT(received, size);
  11623. }
  11624. #endif
  11625. // Forward declaration (see the base64_encode note).
  11626. namespace httplib {
  11627. namespace detail {
  11628. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11629. const std::string &content_type,
  11630. EncodingType encoding);
  11631. } // namespace detail
  11632. } // namespace httplib
  11633. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11634. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11635. ASSERT_TRUE(mm->is_open());
  11636. Response res;
  11637. detail::set_file_content_provider(res, mm, "text/html",
  11638. detail::EncodingType::None);
  11639. std::string out;
  11640. DataSink sink;
  11641. sink.write = [&](const char *d, size_t l) {
  11642. out.append(d, l);
  11643. return true;
  11644. };
  11645. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11646. EXPECT_EQ("test.html", out);
  11647. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11648. EXPECT_EQ("test.html", out);
  11649. }
  11650. TEST(LongPollingTest, ClientCloseDetection) {
  11651. Server svr;
  11652. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11653. res.set_chunked_content_provider(
  11654. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11655. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11656. sink.os << "hello";
  11657. auto count = 10;
  11658. while (count > 0 && sink.is_writable()) {
  11659. this_thread::sleep_for(chrono::milliseconds(10));
  11660. count--;
  11661. }
  11662. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11663. return true;
  11664. });
  11665. });
  11666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11667. auto se = detail::scope_exit([&] {
  11668. svr.stop();
  11669. listen_thread.join();
  11670. ASSERT_FALSE(svr.is_running());
  11671. });
  11672. svr.wait_until_ready();
  11673. Client cli("localhost", PORT);
  11674. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11675. EXPECT_EQ("hello", string(data, data_length));
  11676. return false; // close the socket immediately.
  11677. });
  11678. ASSERT_FALSE(res);
  11679. }
  11680. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11681. Server svr;
  11682. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11683. res.set_chunked_content_provider(
  11684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11685. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11686. sink.os << "hello";
  11687. EXPECT_TRUE(sink.os.good());
  11688. // Wait for the client to close the connection
  11689. auto count = 10;
  11690. while (count > 0 && sink.is_writable()) {
  11691. this_thread::sleep_for(chrono::milliseconds(10));
  11692. count--;
  11693. }
  11694. // After client disconnect, write repeatedly until the socket
  11695. // write actually fails (small writes may be absorbed by the
  11696. // kernel buffer)
  11697. std::string chunk(1024, 'x');
  11698. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11699. sink.os << chunk;
  11700. }
  11701. EXPECT_TRUE(sink.os.fail());
  11702. return true;
  11703. });
  11704. });
  11705. auto port = svr.bind_to_any_port("localhost");
  11706. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. listen_thread.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. Client cli("localhost", port);
  11714. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11715. EXPECT_EQ("hello", string(data, data_length));
  11716. return false; // close the socket immediately.
  11717. });
  11718. ASSERT_FALSE(res);
  11719. }
  11720. TEST(GetWithParametersTest, GetWithParameters) {
  11721. Server svr;
  11722. svr.Get("/", [&](const Request &req, Response &) {
  11723. EXPECT_EQ("world", req.get_param_value("hello"));
  11724. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11725. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11726. });
  11727. svr.Get("/params", [&](const Request &req, Response &) {
  11728. EXPECT_EQ("world", req.get_param_value("hello"));
  11729. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11730. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11731. });
  11732. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11733. EXPECT_EQ("resource-id", req.matches[1]);
  11734. EXPECT_EQ("foo", req.get_param_value("param1"));
  11735. EXPECT_EQ("bar", req.get_param_value("param2"));
  11736. });
  11737. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11738. EXPECT_EQ("user-id", req.path_params.at("id"));
  11739. EXPECT_EQ("foo", req.get_param_value("param1"));
  11740. EXPECT_EQ("bar", req.get_param_value("param2"));
  11741. });
  11742. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11743. auto se = detail::scope_exit([&] {
  11744. svr.stop();
  11745. listen_thread.join();
  11746. ASSERT_FALSE(svr.is_running());
  11747. });
  11748. svr.wait_until_ready();
  11749. {
  11750. Client cli(HOST, PORT);
  11751. Params params;
  11752. params.emplace("hello", "world");
  11753. params.emplace("hello2", "world2");
  11754. params.emplace("hello3", "world3");
  11755. auto res = cli.Get("/", params, Headers{});
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. }
  11759. {
  11760. Client cli(HOST, PORT);
  11761. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11763. EXPECT_EQ(StatusCode::OK_200, res->status);
  11764. }
  11765. {
  11766. Client cli(HOST, PORT);
  11767. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11769. EXPECT_EQ(StatusCode::OK_200, res->status);
  11770. }
  11771. {
  11772. Client cli(HOST, PORT);
  11773. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11775. EXPECT_EQ(StatusCode::OK_200, res->status);
  11776. }
  11777. }
  11778. TEST(GetWithParametersTest, GetWithParameters2) {
  11779. Server svr;
  11780. svr.Get("/", [&](const Request &req, Response &res) {
  11781. auto text = req.get_param_value("hello");
  11782. res.set_content(text, "text/plain");
  11783. });
  11784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. listen_thread.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. Client cli("localhost", PORT);
  11792. Params params;
  11793. params.emplace("hello", "world");
  11794. std::string body;
  11795. auto res = cli.Get("/", params, Headers{},
  11796. [&](const char *data, size_t data_length) {
  11797. body.append(data, data_length);
  11798. return true;
  11799. });
  11800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11801. EXPECT_EQ(StatusCode::OK_200, res->status);
  11802. EXPECT_EQ("world", body);
  11803. }
  11804. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11805. Server svr;
  11806. svr.Get("/search", [&](const Request &req, Response &res) {
  11807. auto q = req.get_param_value("q");
  11808. res.set_content(q, "text/plain");
  11809. });
  11810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. listen_thread.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. Client cli("localhost", PORT);
  11818. // Verify that Get(path, params) works without requiring Headers argument
  11819. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11821. EXPECT_EQ(StatusCode::OK_200, res->status);
  11822. EXPECT_EQ("cpp-httplib", res->body);
  11823. }
  11824. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11825. auto host = "httpbingo.org";
  11826. auto path = std::string{"/range/32"};
  11827. #ifdef CPPHTTPLIB_SSL_ENABLED
  11828. SSLClient cli(host);
  11829. #else
  11830. Client cli(host);
  11831. #endif
  11832. cli.set_default_headers({make_range_header({{1, 10}})});
  11833. cli.set_connection_timeout(5);
  11834. {
  11835. auto res = cli.Get(path);
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. EXPECT_EQ("bcdefghijk", res->body);
  11838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11839. }
  11840. {
  11841. auto res = cli.Get(path);
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ("bcdefghijk", res->body);
  11844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11845. }
  11846. }
  11847. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11848. Server svr;
  11849. svr.set_default_headers({{"Hello", "World"}});
  11850. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11851. res.set_content("ok", "text/plain");
  11852. });
  11853. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11854. auto se = detail::scope_exit([&] {
  11855. svr.stop();
  11856. listen_thread.join();
  11857. ASSERT_FALSE(svr.is_running());
  11858. });
  11859. svr.wait_until_ready();
  11860. Client cli("localhost", PORT);
  11861. auto res = cli.Get("/");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. EXPECT_EQ(StatusCode::OK_200, res->status);
  11864. EXPECT_EQ("ok", res->body);
  11865. EXPECT_EQ("World", res->get_header_value("Hello"));
  11866. }
  11867. #ifdef CPPHTTPLIB_SSL_ENABLED
  11868. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11870. ASSERT_TRUE(svr.is_valid());
  11871. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11872. std::this_thread::sleep_for(std::chrono::seconds(2));
  11873. res.set_content("a", "text/plain");
  11874. });
  11875. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11876. res.set_content("b", "text/plain");
  11877. });
  11878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11879. auto se = detail::scope_exit([&] {
  11880. svr.stop();
  11881. listen_thread.join();
  11882. ASSERT_FALSE(svr.is_running());
  11883. });
  11884. svr.wait_until_ready();
  11885. SSLClient cli("localhost", PORT);
  11886. cli.enable_server_certificate_verification(false);
  11887. cli.set_keep_alive(true);
  11888. cli.set_read_timeout(std::chrono::seconds(1));
  11889. auto resa = cli.Get("/a");
  11890. ASSERT_TRUE(!resa);
  11891. EXPECT_EQ(Error::Read, resa.error());
  11892. auto resb = cli.Get("/b");
  11893. ASSERT_TRUE(resb);
  11894. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11895. EXPECT_EQ("b", resb->body);
  11896. }
  11897. // Closing an idle keep-alive connection sends close_notify and returns. The
  11898. // server must not wait for the client's close_notify: an idle client never
  11899. // sends one, so the worker would be held until the read timeout expires, and
  11900. // stop() would wait for it.
  11901. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11903. ASSERT_TRUE(svr.is_valid());
  11904. svr.set_keep_alive_timeout(1);
  11905. svr.set_read_timeout(10, 0);
  11906. svr.Get("/", [](const Request &, Response &res) {
  11907. res.set_content("ok", "text/plain");
  11908. });
  11909. auto port = svr.bind_to_any_port(HOST);
  11910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11911. auto se = detail::scope_exit([&] {
  11912. if (listen_thread.joinable()) {
  11913. svr.stop();
  11914. listen_thread.join();
  11915. }
  11916. });
  11917. svr.wait_until_ready();
  11918. SSLClient cli(HOST, port);
  11919. cli.enable_server_certificate_verification(false);
  11920. cli.set_keep_alive(true);
  11921. auto res = cli.Get("/");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::OK_200, res->status);
  11924. // Stay idle past the keep-alive timeout so the server closes the connection.
  11925. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11926. auto start = std::chrono::steady_clock::now();
  11927. svr.stop();
  11928. listen_thread.join();
  11929. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11930. std::chrono::steady_clock::now() - start)
  11931. .count();
  11932. EXPECT_LT(elapsed, 3000);
  11933. }
  11934. #endif
  11935. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11936. protected:
  11937. ServerTestWithAI_PASSIVE()
  11938. : cli_(HOST, PORT)
  11939. #ifdef CPPHTTPLIB_SSL_ENABLED
  11940. ,
  11941. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11942. #endif
  11943. {
  11944. #ifdef CPPHTTPLIB_SSL_ENABLED
  11945. cli_.enable_server_certificate_verification(false);
  11946. #endif
  11947. }
  11948. virtual void SetUp() {
  11949. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11950. res.set_content("Hello World!", "text/plain");
  11951. });
  11952. t_ = thread(
  11953. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11954. svr_.wait_until_ready();
  11955. }
  11956. virtual void TearDown() {
  11957. svr_.stop();
  11958. t_.join();
  11959. }
  11960. #ifdef CPPHTTPLIB_SSL_ENABLED
  11961. SSLClient cli_;
  11962. SSLServer svr_;
  11963. #else
  11964. Client cli_;
  11965. Server svr_;
  11966. #endif
  11967. thread t_;
  11968. };
  11969. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11970. auto res = cli_.Get("/hi");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11972. EXPECT_EQ(StatusCode::OK_200, res->status);
  11973. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11974. EXPECT_EQ("Hello World!", res->body);
  11975. }
  11976. class ServerUpDownTest : public ::testing::Test {
  11977. protected:
  11978. ServerUpDownTest() : cli_(HOST, PORT) {}
  11979. virtual void SetUp() {
  11980. t_ = thread([&]() {
  11981. svr_.bind_to_any_port(HOST);
  11982. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11983. ASSERT_TRUE(svr_.listen_after_bind());
  11984. });
  11985. svr_.wait_until_ready();
  11986. }
  11987. virtual void TearDown() {
  11988. svr_.stop();
  11989. t_.join();
  11990. }
  11991. Client cli_;
  11992. Server svr_;
  11993. thread t_;
  11994. };
  11995. TEST_F(ServerUpDownTest, QuickStartStop) {
  11996. // Should not crash, especially when run with
  11997. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11998. }
  11999. class PayloadMaxLengthTest : public ::testing::Test {
  12000. protected:
  12001. PayloadMaxLengthTest()
  12002. : cli_(HOST, PORT)
  12003. #ifdef CPPHTTPLIB_SSL_ENABLED
  12004. ,
  12005. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12006. #endif
  12007. {
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. cli_.enable_server_certificate_verification(false);
  12010. #endif
  12011. }
  12012. virtual void SetUp() {
  12013. svr_.set_payload_max_length(8);
  12014. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12015. res.set_content("test", "text/plain");
  12016. });
  12017. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12018. svr_.wait_until_ready();
  12019. }
  12020. virtual void TearDown() {
  12021. svr_.stop();
  12022. t_.join();
  12023. }
  12024. #ifdef CPPHTTPLIB_SSL_ENABLED
  12025. SSLClient cli_;
  12026. SSLServer svr_;
  12027. #else
  12028. Client cli_;
  12029. Server svr_;
  12030. #endif
  12031. thread t_;
  12032. };
  12033. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12034. auto res = cli_.Post("/test", "123456789", "text/plain");
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12037. res = cli_.Post("/test", "12345678", "text/plain");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. }
  12041. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12042. // Test chunked encoding with payload exceeding the 8-byte limit
  12043. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12044. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12046. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12047. }
  12048. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12049. // Test chunked encoding with payload within the 8-byte limit
  12050. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12051. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12053. EXPECT_EQ(StatusCode::OK_200, res->status);
  12054. }
  12055. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12056. // Test using send_request to send chunked data exceeding payload limit
  12057. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12058. "Host: " +
  12059. std::string(HOST) + ":" + std::to_string(PORT) +
  12060. "\r\n"
  12061. "Transfer-Encoding: chunked\r\n"
  12062. "Connection: close\r\n"
  12063. "\r\n"
  12064. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12065. "0123456789\r\n"
  12066. "0\r\n" // End chunk
  12067. "\r\n";
  12068. std::string response;
  12069. bool result = send_request(1, chunked_request, &response);
  12070. if (!result) {
  12071. // If send_request fails, it might be because the server closed the
  12072. // connection due to payload limit enforcement, which is acceptable
  12073. SUCCEED()
  12074. << "Server rejected oversized chunked request (connection closed)";
  12075. } else {
  12076. // If we got a response, check if it's an error response or connection was
  12077. // closed early Short response length indicates connection was closed due to
  12078. // payload limit
  12079. if (response.length() <= 10) {
  12080. SUCCEED() << "Server closed connection for oversized chunked request";
  12081. } else {
  12082. // Check for error status codes
  12083. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12084. response.find("Payload Too Large") != std::string::npos ||
  12085. response.find("400") != std::string::npos);
  12086. }
  12087. }
  12088. }
  12089. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12090. // Test request without Content-Length header exceeding payload limit
  12091. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12092. "Host: " +
  12093. std::string(HOST) + ":" +
  12094. std::to_string(PORT) +
  12095. "\r\n"
  12096. "Connection: close\r\n"
  12097. "\r\n";
  12098. // Add payload exceeding the 8-byte limit
  12099. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12100. request_without_content_length += large_payload;
  12101. std::string response;
  12102. bool result = send_request(1, request_without_content_length, &response);
  12103. if (!result) {
  12104. // If send_request fails, server likely closed connection due to payload
  12105. // limit
  12106. SUCCEED() << "Server rejected oversized request without Content-Length "
  12107. "(connection closed)";
  12108. } else {
  12109. // Check if server responded with error or closed connection early
  12110. if (response.length() <= 10) {
  12111. SUCCEED() << "Server closed connection for oversized request without "
  12112. "Content-Length";
  12113. } else {
  12114. // Check for error status codes
  12115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12116. response.find("Payload Too Large") != std::string::npos ||
  12117. response.find("400") != std::string::npos);
  12118. }
  12119. }
  12120. }
  12121. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12122. // Test request without Content-Length header within payload limit
  12123. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12124. "Host: " +
  12125. std::string(HOST) + ":" +
  12126. std::to_string(PORT) +
  12127. "\r\n"
  12128. "Connection: close\r\n"
  12129. "\r\n";
  12130. // Add payload within the 8-byte limit
  12131. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12132. request_without_content_length += small_payload;
  12133. std::string response;
  12134. bool result = send_request(1, request_without_content_length, &response);
  12135. // For requests without Content-Length, the server may have different behavior
  12136. // The key is that it should not reject due to payload limit for small
  12137. // payloads
  12138. if (result) {
  12139. // Check for any HTTP response (success or error, but not connection closed)
  12140. if (response.length() > 10) {
  12141. SUCCEED()
  12142. << "Server processed request without Content-Length within limit";
  12143. } else {
  12144. // Short response might indicate connection closed, which is acceptable
  12145. SUCCEED() << "Server closed connection for request without "
  12146. "Content-Length (acceptable behavior)";
  12147. }
  12148. } else {
  12149. // Connection failure might be due to protocol requirements
  12150. SUCCEED() << "Connection issue with request without Content-Length "
  12151. "(environment-specific)";
  12152. }
  12153. }
  12154. class LargePayloadMaxLengthTest : public ::testing::Test {
  12155. protected:
  12156. LargePayloadMaxLengthTest()
  12157. : cli_(HOST, PORT)
  12158. #ifdef CPPHTTPLIB_SSL_ENABLED
  12159. ,
  12160. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12161. #endif
  12162. {
  12163. #ifdef CPPHTTPLIB_SSL_ENABLED
  12164. cli_.enable_server_certificate_verification(false);
  12165. #endif
  12166. }
  12167. virtual void SetUp() {
  12168. // Set 10MB payload limit
  12169. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12170. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12171. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12172. res.set_content("Large payload test", "text/plain");
  12173. });
  12174. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12175. svr_.wait_until_ready();
  12176. }
  12177. virtual void TearDown() {
  12178. svr_.stop();
  12179. t_.join();
  12180. }
  12181. #ifdef CPPHTTPLIB_SSL_ENABLED
  12182. SSLClient cli_;
  12183. SSLServer svr_;
  12184. #else
  12185. Client cli_;
  12186. Server svr_;
  12187. #endif
  12188. thread t_;
  12189. };
  12190. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12191. // Test chunked encoding with payload within 10MB limit
  12192. std::string medium_payload(5 * 1024 * 1024,
  12193. 'A'); // 5MB payload, within 10MB limit
  12194. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12196. EXPECT_EQ(StatusCode::OK_200, res->status);
  12197. }
  12198. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12199. // Test chunked encoding with payload exceeding 10MB limit
  12200. std::string large_payload(12 * 1024 * 1024,
  12201. 'B'); // 12MB payload, exceeds 10MB limit
  12202. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12203. // Server may either return 413 or close the connection
  12204. if (res) {
  12205. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12206. } else {
  12207. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12208. }
  12209. }
  12210. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12211. // Test request without Content-Length header within 10MB limit
  12212. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12213. "Host: " +
  12214. std::string(HOST) + ":" +
  12215. std::to_string(PORT) +
  12216. "\r\n"
  12217. "Connection: close\r\n"
  12218. "\r\n";
  12219. // Add 1MB payload (within 10MB limit)
  12220. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12221. request_without_content_length += medium_payload;
  12222. std::string response;
  12223. bool result = send_request(5, request_without_content_length, &response);
  12224. if (result) {
  12225. // Should get a proper HTTP response for payloads within limit
  12226. if (response.length() > 10) {
  12227. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12228. "10MB limit";
  12229. } else {
  12230. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12231. "Content-Length)";
  12232. }
  12233. } else {
  12234. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12235. }
  12236. }
  12237. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12238. // Test request without Content-Length header exceeding 10MB limit
  12239. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12240. "Host: " +
  12241. std::string(HOST) + ":" +
  12242. std::to_string(PORT) +
  12243. "\r\n"
  12244. "Connection: close\r\n"
  12245. "\r\n";
  12246. // Add 12MB payload (exceeds 10MB limit)
  12247. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12248. request_without_content_length += large_payload;
  12249. std::string response;
  12250. bool result = send_request(10, request_without_content_length, &response);
  12251. if (!result) {
  12252. // Server should close connection due to payload limit
  12253. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12254. "(connection closed)";
  12255. } else {
  12256. // Check for error response
  12257. if (response.length() <= 10) {
  12258. SUCCEED()
  12259. << "Server closed connection for 12MB request exceeding 10MB limit";
  12260. } else {
  12261. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12262. response.find("Payload Too Large") != std::string::npos ||
  12263. response.find("400") != std::string::npos);
  12264. }
  12265. }
  12266. }
  12267. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12268. Server svr;
  12269. svr.Get("/", [](const Request &, Response &res) {
  12270. // Claims the most the client accepts, far more than it sends, then drops
  12271. // the connection.
  12272. res.set_content_provider(std::string().max_size(), "text/plain",
  12273. [](size_t, size_t, DataSink &sink) {
  12274. sink.write("abc", 3);
  12275. return false;
  12276. });
  12277. });
  12278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. thread.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, PORT);
  12286. cli.set_payload_max_length(0);
  12287. EXPECT_FALSE(cli.Get("/"));
  12288. }
  12289. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12290. // Stream API does, not as a plain read failure
  12291. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12292. Server svr;
  12293. svr.Get("/big", [](const Request &, Response &res) {
  12294. res.set_content(std::string(100000, 'b'), "text/plain");
  12295. });
  12296. auto port = svr.bind_to_any_port(HOST);
  12297. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. thread.join();
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, port);
  12304. cli.set_payload_max_length(1000);
  12305. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12306. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12307. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12308. [](const char *, size_t) { return true; });
  12309. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12311. // Small on the wire, over the limit once decompressed
  12312. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12313. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12314. #endif
  12315. }
  12316. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12317. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12318. // path.
  12319. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12320. Server svr;
  12321. const size_t LIMIT = 64 * 1024; // 64KB
  12322. svr.set_payload_max_length(LIMIT);
  12323. size_t total = 0;
  12324. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12325. const ContentReader &content_reader) {
  12326. content_reader([&](const char * /*data*/, size_t len) {
  12327. total += len;
  12328. return true;
  12329. });
  12330. res.status = 200;
  12331. res.set_content("stream_ok", "text/plain");
  12332. });
  12333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. thread.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. });
  12339. svr.wait_until_ready();
  12340. // Prepare 256KB raw data and gzip-compress it
  12341. std::string raw(256 * 1024, 'A');
  12342. std::string gz;
  12343. {
  12344. z_stream zs{};
  12345. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12346. Z_DEFAULT_STRATEGY);
  12347. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12348. zs.avail_in = static_cast<uInt>(raw.size());
  12349. char outbuf[4096];
  12350. int ret;
  12351. do {
  12352. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12353. zs.avail_out = sizeof(outbuf);
  12354. ret = deflate(&zs, Z_FINISH);
  12355. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12356. } while (ret != Z_STREAM_END);
  12357. deflateEnd(&zs);
  12358. }
  12359. Client cli(HOST, PORT);
  12360. cli.set_connection_timeout(std::chrono::seconds(5));
  12361. Headers headers = {{"Content-Encoding", "gzip"}};
  12362. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12363. "application/octet-stream");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. // Server must reject oversized decompressed payloads with 413.
  12366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12367. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12368. EXPECT_LE(total, LIMIT);
  12369. }
  12370. #ifndef CPPHTTPLIB_SSL_ENABLED
  12371. // For a request with neither Content-Length nor Transfer-Encoding, the
  12372. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12373. // compressed wire bytes straight to the ContentReader without ever routing
  12374. // them through the decompressor, so payload_max_length_ only bounded the
  12375. // compressed size on the wire, not the decompressed size.
  12376. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12377. Server svr;
  12378. const size_t LIMIT = 64 * 1024; // 64KB
  12379. svr.set_payload_max_length(LIMIT);
  12380. size_t total = 0;
  12381. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12382. const ContentReader &content_reader) {
  12383. content_reader([&](const char * /*data*/, size_t len) {
  12384. total += len;
  12385. return true;
  12386. });
  12387. res.status = 200;
  12388. res.set_content("stream_ok", "text/plain");
  12389. });
  12390. auto port = svr.bind_to_any_port(HOST);
  12391. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12392. auto se = detail::scope_exit([&] {
  12393. svr.stop();
  12394. thread.join();
  12395. ASSERT_FALSE(svr.is_running());
  12396. });
  12397. svr.wait_until_ready();
  12398. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12399. // StreamingGzipDecompression test above.
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. httplib::detail::gzip_compressor compressor;
  12404. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12405. [&](const char *chunk, size_t len) {
  12406. gz.append(chunk, len);
  12407. return true;
  12408. });
  12409. ASSERT_TRUE(result);
  12410. }
  12411. // Send the gzip body over raw TCP with neither Content-Length nor
  12412. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12413. // kicks in.
  12414. std::string req = "POST /stream HTTP/1.1\r\n"
  12415. "Host: " +
  12416. std::string(HOST) + ":" + std::to_string(port) +
  12417. "\r\n"
  12418. "Content-Encoding: gzip\r\n"
  12419. "Connection: close\r\n"
  12420. "\r\n" +
  12421. gz;
  12422. std::string response;
  12423. ASSERT_TRUE(send_request(5, req, &response, port));
  12424. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12425. EXPECT_LE(total, LIMIT);
  12426. }
  12427. #endif
  12428. #endif
  12429. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12430. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12431. // the payload must be passed through untouched instead of being rejected.
  12432. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12433. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12434. Server svr;
  12435. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(body, "image/jpeg");
  12437. res.set_header("Content-Encoding", "UTF-8");
  12438. });
  12439. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12440. res.set_content(body, "image/jpeg");
  12441. res.set_header("Content-Encoding", "identity");
  12442. });
  12443. svr.Post("/echo", [](const Request &req, Response &res) {
  12444. res.set_content(req.body, "image/jpeg");
  12445. });
  12446. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. t.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. Client cli(HOST, PORT);
  12454. {
  12455. auto res = cli.Get("/image");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. EXPECT_EQ(StatusCode::OK_200, res->status);
  12458. EXPECT_EQ(body, res->body);
  12459. }
  12460. {
  12461. auto res = cli.Get("/identity");
  12462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12463. EXPECT_EQ(StatusCode::OK_200, res->status);
  12464. EXPECT_EQ(body, res->body);
  12465. }
  12466. {
  12467. // The same applies to a request body reaching the server.
  12468. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12469. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ(StatusCode::OK_200, res->status);
  12472. EXPECT_EQ(body, res->body);
  12473. }
  12474. }
  12475. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12476. // gzip-encoded response even when the build has no zlib support.
  12477. static const char GZIPPED_HELLO_WORLD[] = {
  12478. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12479. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12480. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12481. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12482. // A content coding is a whole token, not something the field value merely
  12483. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12484. // as "fibre" look like Brotli, and turned a multi-coding value like
  12485. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12486. // it was never meant to see.
  12487. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12488. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12489. Server svr;
  12490. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12491. res.set_content(body, "image/jpeg");
  12492. res.set_header("Content-Encoding", "fibre");
  12493. });
  12494. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12495. res.set_content(body, "image/jpeg");
  12496. res.set_header("Content-Encoding", "gzip, br");
  12497. });
  12498. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12499. res.set_content(body, "image/jpeg");
  12500. res.set_header("Content-Encoding", "x-zstd-ish");
  12501. });
  12502. auto port = svr.bind_to_any_port(HOST);
  12503. thread t = thread([&]() { svr.listen_after_bind(); });
  12504. auto se = detail::scope_exit([&] {
  12505. svr.stop();
  12506. t.join();
  12507. ASSERT_FALSE(svr.is_running());
  12508. });
  12509. svr.wait_until_ready();
  12510. Client cli(HOST, port);
  12511. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12512. auto res = cli.Get(path);
  12513. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12514. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12515. // Not a coding we recognize, so the payload comes back untouched
  12516. EXPECT_EQ(body, res->body) << path;
  12517. }
  12518. }
  12519. // A content coding cpp-httplib recognizes but was not built with must be
  12520. // reported as such. Handing the still-compressed payload back to the caller
  12521. // would silently corrupt it.
  12522. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12523. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12524. Server svr;
  12525. // "image/jpeg" keeps the server from applying a content coding of its own,
  12526. // so the hand-crafted Content-Encoding below survives.
  12527. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(gzipped, "image/jpeg");
  12529. res.set_header("Content-Encoding", "gzip");
  12530. });
  12531. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12532. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12533. res.set_content(gzipped, "image/jpeg");
  12534. res.set_header("Content-Encoding", "GZIP");
  12535. });
  12536. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12537. auto se = detail::scope_exit([&] {
  12538. svr.stop();
  12539. t.join();
  12540. ASSERT_FALSE(svr.is_running());
  12541. });
  12542. svr.wait_until_ready();
  12543. Client cli(HOST, PORT);
  12544. {
  12545. auto res = cli.Get("/gzipped");
  12546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_EQ("Hello World!", res->body);
  12549. #else
  12550. ASSERT_FALSE(res);
  12551. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12552. #endif
  12553. }
  12554. {
  12555. // open_stream() must behave the same way.
  12556. auto handle = cli.open_stream("GET", "/gzipped");
  12557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12558. ASSERT_TRUE(handle.is_valid());
  12559. std::string received;
  12560. char buf[256];
  12561. ssize_t n;
  12562. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12563. received.append(buf, static_cast<size_t>(n));
  12564. }
  12565. EXPECT_EQ("Hello World!", received);
  12566. #else
  12567. EXPECT_FALSE(handle.is_valid());
  12568. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12569. #endif
  12570. }
  12571. {
  12572. // A differently-cased coding must not be mistaken for an unknown one, or
  12573. // the body would be handed back still compressed.
  12574. auto res = cli.Get("/gzipped-uppercase");
  12575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. EXPECT_EQ("Hello World!", res->body);
  12578. #else
  12579. ASSERT_FALSE(res);
  12580. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12581. #endif
  12582. }
  12583. }
  12584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12585. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12586. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12587. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12588. // body a second time and appending a second Content-Encoding field line, so
  12589. // clients that decode one coding per listed value handed back raw gzip bytes.
  12590. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12591. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12592. Server svr;
  12593. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12594. // keeps the server from applying a coding of its own.
  12595. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12596. res.set_content(gzipped, "text/plain");
  12597. res.set_header("Content-Encoding", "gzip");
  12598. });
  12599. auto port = svr.bind_to_any_port(HOST);
  12600. thread t = thread([&]() { svr.listen_after_bind(); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. t.join();
  12604. ASSERT_FALSE(svr.is_running());
  12605. });
  12606. svr.wait_until_ready();
  12607. Client cli(HOST, port);
  12608. Headers headers = {{"Accept-Encoding", "gzip"}};
  12609. auto res = cli.Get("/pre-gzipped", headers);
  12610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12611. EXPECT_EQ(StatusCode::OK_200, res->status);
  12612. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12613. EXPECT_EQ("Hello World!", res->body);
  12614. }
  12615. // set_compress(false) sends every handler response as it is, buffered or
  12616. // streamed
  12617. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12618. const std::string text(1000, 'a');
  12619. Server svr;
  12620. svr.set_compress(false);
  12621. svr.Get("/buffered", [&](const Request &, Response &res) {
  12622. res.set_content(text, "text/plain");
  12623. });
  12624. svr.Get("/streamed", [&](const Request &, Response &res) {
  12625. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12626. sink.write(text.data(), text.size());
  12627. sink.done();
  12628. return true;
  12629. });
  12630. });
  12631. auto port = svr.bind_to_any_port(HOST);
  12632. ASSERT_LT(0, port);
  12633. thread t = thread([&] { svr.listen_after_bind(); });
  12634. auto se = detail::scope_exit([&] {
  12635. svr.stop();
  12636. t.join();
  12637. ASSERT_FALSE(svr.is_running());
  12638. });
  12639. svr.wait_until_ready();
  12640. Client cli(HOST, port);
  12641. cli.set_decompress(false);
  12642. for (auto path : {"/buffered", "/streamed"}) {
  12643. SCOPED_TRACE(path);
  12644. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12646. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12647. EXPECT_EQ(text, res->body);
  12648. }
  12649. }
  12650. // A chunked provider settles its coding where the headers are written and
  12651. // reuses it at write time. Both ends of that have to hold: a handler's own
  12652. // Content-Encoding suppresses the coding, and a response without one is still
  12653. // compressed as it always was.
  12654. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12655. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12656. const std::string plain = "Hello World! Hello World! Hello World!";
  12657. Server svr;
  12658. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12659. res.set_header("Content-Encoding", "gzip");
  12660. res.set_chunked_content_provider(
  12661. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12662. sink.write(gzipped.data(), gzipped.size());
  12663. sink.done();
  12664. return true;
  12665. });
  12666. });
  12667. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12668. res.set_chunked_content_provider(
  12669. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12670. sink.write(plain.data(), plain.size());
  12671. sink.done();
  12672. return true;
  12673. });
  12674. });
  12675. auto port = svr.bind_to_any_port(HOST);
  12676. thread t = thread([&]() { svr.listen_after_bind(); });
  12677. auto se = detail::scope_exit([&] {
  12678. svr.stop();
  12679. t.join();
  12680. ASSERT_FALSE(svr.is_running());
  12681. });
  12682. svr.wait_until_ready();
  12683. Client cli(HOST, port);
  12684. Headers headers = {{"Accept-Encoding", "gzip"}};
  12685. {
  12686. auto res = cli.Get("/pre-gzipped", headers);
  12687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12688. EXPECT_EQ(StatusCode::OK_200, res->status);
  12689. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12690. EXPECT_EQ("Hello World!", res->body);
  12691. }
  12692. {
  12693. auto res = cli.Get("/negotiated", headers);
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_EQ(StatusCode::OK_200, res->status);
  12696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12697. EXPECT_EQ(plain, res->body);
  12698. }
  12699. }
  12700. #endif
  12701. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12702. // the same message as the comma-joined one, so both have to be read the same
  12703. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12704. // single gzip coding, and a body the sender says was encoded twice was handed
  12705. // back after one pass, still compressed but presented as decoded.
  12706. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12707. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12708. Server svr;
  12709. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12710. res.set_content(body, "image/jpeg");
  12711. res.headers.emplace("Content-Encoding", "gzip");
  12712. res.headers.emplace("Content-Encoding", "gzip");
  12713. });
  12714. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12715. res.set_content(body, "image/jpeg");
  12716. res.set_header("Content-Encoding", "gzip, gzip");
  12717. });
  12718. auto port = svr.bind_to_any_port(HOST);
  12719. thread t = thread([&]() { svr.listen_after_bind(); });
  12720. auto se = detail::scope_exit([&] {
  12721. svr.stop();
  12722. t.join();
  12723. ASSERT_FALSE(svr.is_running());
  12724. });
  12725. svr.wait_until_ready();
  12726. Client cli(HOST, port);
  12727. // Two codings is not something cpp-httplib decodes, so both representations
  12728. // take the pass-through path rather than one of them being gunzipped once.
  12729. for (const char *path : {"/split", "/joined"}) {
  12730. auto res = cli.Get(path);
  12731. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12732. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12733. EXPECT_EQ(body, res->body) << path;
  12734. }
  12735. }
  12736. // Regression test for DoS vulnerability: a malicious server sending a response
  12737. // without Content-Length header must not cause unbounded memory consumption on
  12738. // the client side. The client should stop reading after a reasonable limit,
  12739. // similar to the server-side set_payload_max_length protection.
  12740. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12741. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12742. #ifndef _WIN32
  12743. signal(SIGPIPE, SIG_IGN);
  12744. #endif
  12745. auto server_thread = std::thread([] {
  12746. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12747. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12748. default_socket_options(srv);
  12749. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12751. sockaddr_in addr{};
  12752. addr.sin_family = AF_INET;
  12753. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12754. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12755. int opt = 1;
  12756. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12757. #ifdef _WIN32
  12758. reinterpret_cast<const char *>(&opt),
  12759. #else
  12760. &opt,
  12761. #endif
  12762. sizeof(opt));
  12763. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12764. ::listen(srv, 1);
  12765. sockaddr_in cli_addr{};
  12766. socklen_t cli_len = sizeof(cli_addr);
  12767. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12768. if (cli != INVALID_SOCKET) {
  12769. char buf[4096];
  12770. ::recv(cli, buf, sizeof(buf), 0);
  12771. // Malicious response: no Content-Length, no chunked encoding
  12772. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12773. "Connection: close\r\n"
  12774. "\r\n";
  12775. ::send(cli,
  12776. #ifdef _WIN32
  12777. static_cast<const char *>(response_header.c_str()),
  12778. static_cast<int>(response_header.size()),
  12779. #else
  12780. response_header.c_str(), response_header.size(),
  12781. #endif
  12782. 0);
  12783. // Send 10MB of data
  12784. std::string chunk(64 * 1024, 'A');
  12785. size_t total_sent = 0;
  12786. while (total_sent < MALICIOUS_DATA_SIZE) {
  12787. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12788. auto sent = ::send(cli,
  12789. #ifdef _WIN32
  12790. static_cast<const char *>(chunk.c_str()),
  12791. static_cast<int>(to_send),
  12792. #else
  12793. chunk.c_str(), to_send,
  12794. #endif
  12795. 0);
  12796. if (sent <= 0) break;
  12797. total_sent += static_cast<size_t>(sent);
  12798. }
  12799. detail::close_socket(cli);
  12800. }
  12801. detail::close_socket(srv);
  12802. });
  12803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12804. size_t total_read = 0;
  12805. {
  12806. Client cli("127.0.0.1", PORT + 2);
  12807. cli.set_read_timeout(5, 0);
  12808. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12809. auto stream = cli.open_stream("GET", "/malicious");
  12810. ASSERT_TRUE(stream.is_valid());
  12811. char buffer[64 * 1024];
  12812. ssize_t n;
  12813. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12814. total_read += static_cast<size_t>(n);
  12815. }
  12816. } // StreamHandle and Client destroyed here, closing the socket
  12817. server_thread.join();
  12818. // With set_payload_max_length, the client must stop reading before consuming
  12819. // all 10MB. The read loop should be cut off at or near the configured limit.
  12820. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12821. << "Client read " << total_read << " bytes, exceeding the configured "
  12822. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12823. }
  12824. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12825. // the entire response body without truncation.
  12826. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12827. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12828. #ifndef _WIN32
  12829. signal(SIGPIPE, SIG_IGN);
  12830. #endif
  12831. auto server_thread = std::thread([] {
  12832. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12833. default_socket_options(srv);
  12834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12836. sockaddr_in addr{};
  12837. addr.sin_family = AF_INET;
  12838. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12840. int opt = 1;
  12841. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12842. #ifdef _WIN32
  12843. reinterpret_cast<const char *>(&opt),
  12844. #else
  12845. &opt,
  12846. #endif
  12847. sizeof(opt));
  12848. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12849. ::listen(srv, 1);
  12850. sockaddr_in cli_addr{};
  12851. socklen_t cli_len = sizeof(cli_addr);
  12852. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12853. if (cli != INVALID_SOCKET) {
  12854. char buf[4096];
  12855. ::recv(cli, buf, sizeof(buf), 0);
  12856. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12857. "Connection: close\r\n"
  12858. "\r\n";
  12859. ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(response_header.c_str()),
  12862. static_cast<int>(response_header.size()),
  12863. #else
  12864. response_header.c_str(), response_header.size(),
  12865. #endif
  12866. 0);
  12867. std::string chunk(64 * 1024, 'A');
  12868. size_t total_sent = 0;
  12869. while (total_sent < DATA_SIZE) {
  12870. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12871. auto sent = ::send(cli,
  12872. #ifdef _WIN32
  12873. static_cast<const char *>(chunk.c_str()),
  12874. static_cast<int>(to_send),
  12875. #else
  12876. chunk.c_str(), to_send,
  12877. #endif
  12878. 0);
  12879. if (sent <= 0) break;
  12880. total_sent += static_cast<size_t>(sent);
  12881. }
  12882. #ifdef _WIN32
  12883. ::shutdown(cli, SD_SEND);
  12884. #else
  12885. ::shutdown(cli, SHUT_WR);
  12886. #endif
  12887. // Drain until the client closes its end, ensuring all data is delivered
  12888. char drain[1024];
  12889. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12890. detail::close_socket(cli);
  12891. }
  12892. detail::close_socket(srv);
  12893. });
  12894. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12895. size_t total_read = 0;
  12896. {
  12897. Client cli("127.0.0.1", PORT + 2);
  12898. cli.set_read_timeout(5, 0);
  12899. cli.set_payload_max_length(0); // 0 means no limit
  12900. auto stream = cli.open_stream("GET", "/data");
  12901. ASSERT_TRUE(stream.is_valid());
  12902. char buffer[64 * 1024];
  12903. ssize_t n;
  12904. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12905. total_read += static_cast<size_t>(n);
  12906. }
  12907. }
  12908. server_thread.join();
  12909. EXPECT_EQ(total_read, DATA_SIZE)
  12910. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12911. << " bytes without truncation, but only read " << total_read << " bytes.";
  12912. }
  12913. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12914. // enormous Content-Length must not cause the client to pre-allocate a huge
  12915. // response body buffer. The reservation is capped at payload_max_length_, and
  12916. // the read itself fails when the body exceeds the limit.
  12917. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12918. #ifndef _WIN32
  12919. signal(SIGPIPE, SIG_IGN);
  12920. #endif
  12921. auto server_thread = std::thread([] {
  12922. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12923. default_socket_options(srv);
  12924. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12926. sockaddr_in addr{};
  12927. addr.sin_family = AF_INET;
  12928. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12929. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12930. int opt = 1;
  12931. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12932. #ifdef _WIN32
  12933. reinterpret_cast<const char *>(&opt),
  12934. #else
  12935. &opt,
  12936. #endif
  12937. sizeof(opt));
  12938. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12939. ::listen(srv, 1);
  12940. sockaddr_in cli_addr{};
  12941. socklen_t cli_len = sizeof(cli_addr);
  12942. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12943. if (cli != INVALID_SOCKET) {
  12944. char buf[4096];
  12945. ::recv(cli, buf, sizeof(buf), 0);
  12946. // Malicious response: claim a 20GB body but send only a tiny payload.
  12947. std::string response = "HTTP/1.1 200 OK\r\n"
  12948. "Content-Length: 20000000000\r\n"
  12949. "\r\n"
  12950. "abc";
  12951. ::send(cli,
  12952. #ifdef _WIN32
  12953. static_cast<const char *>(response.c_str()),
  12954. static_cast<int>(response.size()),
  12955. #else
  12956. response.c_str(), response.size(),
  12957. #endif
  12958. 0);
  12959. detail::close_socket(cli);
  12960. }
  12961. detail::close_socket(srv);
  12962. });
  12963. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12964. {
  12965. Client cli("127.0.0.1", PORT + 2);
  12966. cli.set_read_timeout(5, 0);
  12967. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12968. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12969. // (server claims more bytes than payload_max_length permits), but it must
  12970. // not exhaust memory before getting there.
  12971. auto res = cli.Get("/malicious");
  12972. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12973. }
  12974. server_thread.join();
  12975. }
  12976. // Verify that content_receiver bypasses the default payload_max_length,
  12977. // allowing streaming downloads larger than 100MB without requiring an explicit
  12978. // set_payload_max_length call.
  12979. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12980. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12981. #ifndef _WIN32
  12982. signal(SIGPIPE, SIG_IGN);
  12983. #endif
  12984. auto server_thread = std::thread([] {
  12985. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12986. default_socket_options(srv);
  12987. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12989. sockaddr_in addr{};
  12990. addr.sin_family = AF_INET;
  12991. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12992. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12993. int opt = 1;
  12994. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12995. #ifdef _WIN32
  12996. reinterpret_cast<const char *>(&opt),
  12997. #else
  12998. &opt,
  12999. #endif
  13000. sizeof(opt));
  13001. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13002. ::listen(srv, 1);
  13003. sockaddr_in cli_addr{};
  13004. socklen_t cli_len = sizeof(cli_addr);
  13005. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13006. if (cli != INVALID_SOCKET) {
  13007. char buf[4096];
  13008. ::recv(cli, buf, sizeof(buf), 0);
  13009. // Response with Content-Length larger than default 100MB limit
  13010. auto content_length = std::to_string(DATA_SIZE);
  13011. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13012. "Content-Length: " +
  13013. content_length +
  13014. "\r\n"
  13015. "Connection: close\r\n"
  13016. "\r\n";
  13017. ::send(cli,
  13018. #ifdef _WIN32
  13019. static_cast<const char *>(response_header.c_str()),
  13020. static_cast<int>(response_header.size()),
  13021. #else
  13022. response_header.c_str(), response_header.size(),
  13023. #endif
  13024. 0);
  13025. std::string chunk(64 * 1024, 'A');
  13026. size_t total_sent = 0;
  13027. while (total_sent < DATA_SIZE) {
  13028. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13029. auto sent = ::send(cli,
  13030. #ifdef _WIN32
  13031. static_cast<const char *>(chunk.c_str()),
  13032. static_cast<int>(to_send),
  13033. #else
  13034. chunk.c_str(), to_send,
  13035. #endif
  13036. 0);
  13037. if (sent <= 0) break;
  13038. total_sent += static_cast<size_t>(sent);
  13039. }
  13040. detail::close_socket(cli);
  13041. }
  13042. detail::close_socket(srv);
  13043. });
  13044. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13045. size_t total_received = 0;
  13046. {
  13047. Client cli("127.0.0.1", PORT + 2);
  13048. cli.set_read_timeout(10, 0);
  13049. // Do NOT call set_payload_max_length — use the default 100MB limit
  13050. auto res =
  13051. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13052. total_received += data_length;
  13053. return true;
  13054. });
  13055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13056. EXPECT_EQ(StatusCode::OK_200, res->status);
  13057. }
  13058. server_thread.join();
  13059. EXPECT_EQ(total_received, DATA_SIZE)
  13060. << "With content_receiver, the client should read all " << DATA_SIZE
  13061. << " bytes despite the default 100MB payload_max_length, but only read "
  13062. << total_received << " bytes.";
  13063. }
  13064. // Verify that an explicit set_payload_max_length smaller than the response is
  13065. // enforced even when a content_receiver is used.
  13066. TEST(ClientVulnerabilityTest,
  13067. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13068. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13069. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13070. #ifndef _WIN32
  13071. signal(SIGPIPE, SIG_IGN);
  13072. #endif
  13073. auto server_thread = std::thread([] {
  13074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13075. default_socket_options(srv);
  13076. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13078. sockaddr_in addr{};
  13079. addr.sin_family = AF_INET;
  13080. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13081. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13082. int opt = 1;
  13083. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13084. #ifdef _WIN32
  13085. reinterpret_cast<const char *>(&opt),
  13086. #else
  13087. &opt,
  13088. #endif
  13089. sizeof(opt));
  13090. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13091. ::listen(srv, 1);
  13092. sockaddr_in cli_addr{};
  13093. socklen_t cli_len = sizeof(cli_addr);
  13094. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13095. if (cli != INVALID_SOCKET) {
  13096. char buf[4096];
  13097. ::recv(cli, buf, sizeof(buf), 0);
  13098. auto content_length = std::to_string(DATA_SIZE);
  13099. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13100. "Content-Length: " +
  13101. content_length +
  13102. "\r\n"
  13103. "Connection: close\r\n"
  13104. "\r\n";
  13105. ::send(cli,
  13106. #ifdef _WIN32
  13107. static_cast<const char *>(response_header.c_str()),
  13108. static_cast<int>(response_header.size()),
  13109. #else
  13110. response_header.c_str(), response_header.size(),
  13111. #endif
  13112. 0);
  13113. std::string chunk(64 * 1024, 'A');
  13114. size_t total_sent = 0;
  13115. while (total_sent < DATA_SIZE) {
  13116. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13117. auto sent = ::send(cli,
  13118. #ifdef _WIN32
  13119. static_cast<const char *>(chunk.c_str()),
  13120. static_cast<int>(to_send),
  13121. #else
  13122. chunk.c_str(), to_send,
  13123. #endif
  13124. 0);
  13125. if (sent <= 0) break;
  13126. total_sent += static_cast<size_t>(sent);
  13127. }
  13128. detail::close_socket(cli);
  13129. }
  13130. detail::close_socket(srv);
  13131. });
  13132. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13133. size_t total_received = 0;
  13134. {
  13135. Client cli("127.0.0.1", PORT + 2);
  13136. cli.set_read_timeout(10, 0);
  13137. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13138. auto res =
  13139. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13140. total_received += data_length;
  13141. return true;
  13142. });
  13143. // Should fail because 200MB exceeds the explicit 150MB limit
  13144. EXPECT_FALSE(res);
  13145. }
  13146. server_thread.join();
  13147. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13148. << "Client with content_receiver should respect the explicit "
  13149. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13150. << total_received << " bytes.";
  13151. }
  13152. // Verify that an explicit set_payload_max_length larger than the response
  13153. // allows the content_receiver to read all data successfully.
  13154. TEST(ClientVulnerabilityTest,
  13155. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13156. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13157. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13158. #ifndef _WIN32
  13159. signal(SIGPIPE, SIG_IGN);
  13160. #endif
  13161. auto server_thread = std::thread([] {
  13162. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13163. default_socket_options(srv);
  13164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13166. sockaddr_in addr{};
  13167. addr.sin_family = AF_INET;
  13168. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13169. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13170. int opt = 1;
  13171. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13172. #ifdef _WIN32
  13173. reinterpret_cast<const char *>(&opt),
  13174. #else
  13175. &opt,
  13176. #endif
  13177. sizeof(opt));
  13178. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13179. ::listen(srv, 1);
  13180. sockaddr_in cli_addr{};
  13181. socklen_t cli_len = sizeof(cli_addr);
  13182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13183. if (cli != INVALID_SOCKET) {
  13184. char buf[4096];
  13185. ::recv(cli, buf, sizeof(buf), 0);
  13186. auto content_length = std::to_string(DATA_SIZE);
  13187. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13188. "Content-Length: " +
  13189. content_length +
  13190. "\r\n"
  13191. "Connection: close\r\n"
  13192. "\r\n";
  13193. ::send(cli,
  13194. #ifdef _WIN32
  13195. static_cast<const char *>(response_header.c_str()),
  13196. static_cast<int>(response_header.size()),
  13197. #else
  13198. response_header.c_str(), response_header.size(),
  13199. #endif
  13200. 0);
  13201. std::string chunk(64 * 1024, 'A');
  13202. size_t total_sent = 0;
  13203. while (total_sent < DATA_SIZE) {
  13204. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13205. auto sent = ::send(cli,
  13206. #ifdef _WIN32
  13207. static_cast<const char *>(chunk.c_str()),
  13208. static_cast<int>(to_send),
  13209. #else
  13210. chunk.c_str(), to_send,
  13211. #endif
  13212. 0);
  13213. if (sent <= 0) break;
  13214. total_sent += static_cast<size_t>(sent);
  13215. }
  13216. #ifdef _WIN32
  13217. ::shutdown(cli, SD_SEND);
  13218. #else
  13219. ::shutdown(cli, SHUT_WR);
  13220. #endif
  13221. char drain[1024];
  13222. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13223. detail::close_socket(cli);
  13224. }
  13225. detail::close_socket(srv);
  13226. });
  13227. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13228. size_t total_received = 0;
  13229. {
  13230. Client cli("127.0.0.1", PORT + 2);
  13231. cli.set_read_timeout(10, 0);
  13232. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13233. auto res =
  13234. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13235. total_received += data_length;
  13236. return true;
  13237. });
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. EXPECT_EQ(StatusCode::OK_200, res->status);
  13240. }
  13241. server_thread.join();
  13242. EXPECT_EQ(total_received, DATA_SIZE)
  13243. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13244. << " bytes (larger than " << DATA_SIZE
  13245. << " bytes response), content_receiver should read all data, but only "
  13246. "read "
  13247. << total_received << " bytes.";
  13248. }
  13249. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13250. // Regression test for "zip bomb" attack on the client side: a malicious server
  13251. // sends a small gzip-compressed response that decompresses to a huge payload.
  13252. // The client must enforce payload_max_length on the decompressed size.
  13253. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13254. constexpr size_t DECOMPRESSED_SIZE =
  13255. 10 * 1024 * 1024; // 10MB after decompression
  13256. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13257. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13258. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13259. std::string compressed;
  13260. {
  13261. httplib::detail::gzip_compressor compressor;
  13262. bool ok =
  13263. compressor.compress(uncompressed.data(), uncompressed.size(),
  13264. /*last=*/true, [&](const char *buf, size_t len) {
  13265. compressed.append(buf, len);
  13266. return true;
  13267. });
  13268. ASSERT_TRUE(ok);
  13269. }
  13270. // Sanity: compressed data should be much smaller than the decompressed size
  13271. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13272. #ifndef _WIN32
  13273. signal(SIGPIPE, SIG_IGN);
  13274. #endif
  13275. // Set up the listening socket in the main thread so the server is guaranteed
  13276. // to be ready before the client connects (eliminates race condition).
  13277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13278. default_socket_options(srv);
  13279. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13281. sockaddr_in addr{};
  13282. addr.sin_family = AF_INET;
  13283. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13285. int opt = 1;
  13286. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13287. #ifdef _WIN32
  13288. reinterpret_cast<const char *>(&opt),
  13289. #else
  13290. &opt,
  13291. #endif
  13292. sizeof(opt));
  13293. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13294. ASSERT_EQ(0, ::listen(srv, 1));
  13295. auto server_thread = std::thread([&compressed, srv] {
  13296. sockaddr_in cli_addr{};
  13297. socklen_t cli_len = sizeof(cli_addr);
  13298. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13299. if (cli != INVALID_SOCKET) {
  13300. // Read the full HTTP request (until \r\n\r\n)
  13301. char buf[4096];
  13302. size_t total = 0;
  13303. while (total < sizeof(buf)) {
  13304. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13305. if (n <= 0) break;
  13306. total += static_cast<size_t>(n);
  13307. // Check for end of headers
  13308. if (total >= 4) {
  13309. std::string req(buf, total);
  13310. if (req.find("\r\n\r\n") != std::string::npos) break;
  13311. }
  13312. }
  13313. // Malicious response: gzip-compressed body, no Content-Length
  13314. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13315. "Content-Encoding: gzip\r\n"
  13316. "Connection: close\r\n"
  13317. "\r\n";
  13318. ::send(cli,
  13319. #ifdef _WIN32
  13320. static_cast<const char *>(response_header.c_str()),
  13321. static_cast<int>(response_header.size()),
  13322. #else
  13323. response_header.c_str(), response_header.size(),
  13324. #endif
  13325. 0);
  13326. // Send the compressed payload (small on the wire, huge when decompressed)
  13327. size_t total_sent = 0;
  13328. while (total_sent < compressed.size()) {
  13329. auto to_send = std::min(compressed.size() - total_sent,
  13330. static_cast<size_t>(64 * 1024));
  13331. auto sent =
  13332. ::send(cli,
  13333. #ifdef _WIN32
  13334. static_cast<const char *>(compressed.c_str() + total_sent),
  13335. static_cast<int>(to_send),
  13336. #else
  13337. compressed.c_str() + total_sent, to_send,
  13338. #endif
  13339. 0);
  13340. if (sent <= 0) break;
  13341. total_sent += static_cast<size_t>(sent);
  13342. }
  13343. detail::close_socket(cli);
  13344. }
  13345. });
  13346. auto se = detail::scope_exit([&] {
  13347. detail::close_socket(srv);
  13348. server_thread.join();
  13349. });
  13350. size_t total_decompressed = 0;
  13351. {
  13352. Client cli("127.0.0.1", PORT + 3);
  13353. cli.set_read_timeout(5, 0);
  13354. cli.set_decompress(true);
  13355. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13356. auto stream = cli.open_stream("GET", "/zipbomb");
  13357. ASSERT_TRUE(stream.is_valid());
  13358. char buffer[64 * 1024];
  13359. ssize_t n;
  13360. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13361. total_decompressed += static_cast<size_t>(n);
  13362. }
  13363. }
  13364. // The decompressed size must be capped by payload_max_length. Without
  13365. // protection, the client would decompress the full 10MB from a tiny
  13366. // compressed payload, enabling a zip bomb DoS attack.
  13367. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13368. << "Client decompressed " << total_decompressed
  13369. << " bytes from a gzip response. The decompressed size should be "
  13370. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13371. }
  13372. #endif
  13373. TEST(HostAndPortPropertiesTest, NoSSL) {
  13374. httplib::Client cli("www.google.com", 1234);
  13375. ASSERT_EQ("www.google.com", cli.host());
  13376. ASSERT_EQ(1234, cli.port());
  13377. }
  13378. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13379. httplib::Client cli("www.google.com:1234");
  13380. ASSERT_EQ("www.google.com", cli.host());
  13381. ASSERT_EQ(1234, cli.port());
  13382. }
  13383. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13384. // Port number that overflows int — should not crash, client becomes invalid
  13385. httplib::Client cli("http://www.google.com:99999999999999999999");
  13386. ASSERT_FALSE(cli.is_valid());
  13387. }
  13388. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13389. // Port 99999 exceeds valid range (1-65535) — should not crash
  13390. httplib::Client cli("http://www.google.com:99999");
  13391. ASSERT_FALSE(cli.is_valid());
  13392. auto res = cli.Get("/");
  13393. EXPECT_FALSE(res);
  13394. EXPECT_EQ(Error::Connection, res.error());
  13395. }
  13396. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13397. httplib::Client cli("http://user:pass@localhost:1234");
  13398. ASSERT_FALSE(cli.is_valid());
  13399. EXPECT_FALSE(cli.Get("/"));
  13400. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13401. }
  13402. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13403. httplib::Client cli("http://www.google.com:80abc");
  13404. ASSERT_FALSE(cli.is_valid());
  13405. }
  13406. #ifdef CPPHTTPLIB_SSL_ENABLED
  13407. TEST(HostAndPortPropertiesTest, SSL) {
  13408. httplib::SSLClient cli("www.google.com");
  13409. ASSERT_EQ("www.google.com", cli.host());
  13410. ASSERT_EQ(443, cli.port());
  13411. }
  13412. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13413. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13414. std::string cert;
  13415. read_file(CA_CERT_FILE, cert);
  13416. httplib::SSLClient httplib_client("www.google.com");
  13417. // Load CA store first time
  13418. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13419. // Load CA store second time (update)
  13420. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13421. // Verify client is still valid and can make connections
  13422. httplib_client.enable_server_certificate_verification(true);
  13423. auto res = httplib_client.Get("/");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. // Google may return 200 or 301 depending on various factors
  13426. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13427. res->status == StatusCode::MovedPermanently_301);
  13428. }
  13429. TEST(SSLClientTest, ServerNameIndication_Online) {
  13430. auto host = "httpbingo.org";
  13431. auto path = std::string{"/get"};
  13432. SSLClient cli(host, 443);
  13433. auto res = cli.Get(path);
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. ASSERT_EQ(StatusCode::OK_200, res->status);
  13436. }
  13437. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13438. // Use a site that will cause SSL verification failure due to self-signed cert
  13439. SSLClient cli("self-signed.badssl.com", 443);
  13440. cli.enable_server_certificate_verification(true);
  13441. auto res = cli.Get("/");
  13442. ASSERT_TRUE(!res);
  13443. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13444. // Verify backend error is captured for SSLServerVerification
  13445. // This occurs when certificate verification fails
  13446. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13447. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13448. EXPECT_NE(0UL, res.ssl_backend_error());
  13449. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13450. res.ssl_error());
  13451. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13452. #if !defined(_WIN32) || \
  13453. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13454. // On non-Windows or when Windows Schannel is disabled, the error comes
  13455. // from OpenSSL's verification
  13456. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13457. res.ssl_backend_error());
  13458. #endif
  13459. #endif
  13460. }
  13461. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13462. // Use a site where hostname doesn't match the certificate
  13463. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13464. SSLClient cli("wrong.host.badssl.com", 443);
  13465. cli.enable_server_certificate_verification(true);
  13466. cli.enable_server_hostname_verification(true);
  13467. auto res = cli.Get("/");
  13468. ASSERT_TRUE(!res);
  13469. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13470. // Verify backend error is captured for hostname verification failure
  13471. EXPECT_NE(0UL, res.ssl_backend_error());
  13472. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13473. res.ssl_error());
  13474. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13475. #if !defined(_WIN32) || \
  13476. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13477. // On non-Windows or when Windows Schannel is disabled, the error comes
  13478. // from OpenSSL's hostname verification
  13479. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13480. res.ssl_backend_error());
  13481. #endif
  13482. #endif
  13483. }
  13484. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13485. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13486. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13487. SSLClient cli("www.google.com", 443);
  13488. cli.enable_server_certificate_verification(true);
  13489. auto res = cli.Get("/");
  13490. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13491. }
  13492. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13493. SSLClient cli("www.google.com", 443);
  13494. cli.enable_server_certificate_verification(true);
  13495. cli.enable_windows_certificate_verification(false);
  13496. auto res = cli.Get("/");
  13497. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13498. }
  13499. // The server sends an intermediate cross-signed by a root Windows trusts,
  13500. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13501. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13502. SSLClient cli("accounts.spotify.com", 443);
  13503. auto res = cli.Get("/");
  13504. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13505. << " ssl_backend_error=" << res.ssl_backend_error();
  13506. }
  13507. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13508. // policy status, which no backend reports for a self-signed certificate.
  13509. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13510. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13511. ASSERT_TRUE(svr.is_valid());
  13512. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13513. auto se = detail::scope_exit([&] {
  13514. svr.stop();
  13515. t.join();
  13516. ASSERT_FALSE(svr.is_running());
  13517. });
  13518. svr.wait_until_ready();
  13519. SSLClient cli("127.0.0.1", PORT);
  13520. cli.set_connection_timeout(30);
  13521. auto res = cli.Get("/");
  13522. ASSERT_FALSE(res);
  13523. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13524. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13525. }
  13526. #endif
  13527. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13528. Client cli("https://google.com");
  13529. auto res = cli.Get("/");
  13530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13531. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13532. }
  13533. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13534. SSLClient cli("google.com");
  13535. cli.set_ca_cert_path(CA_CERT_FILE);
  13536. auto res = cli.Get("/");
  13537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13538. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13539. }
  13540. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13541. SSLClient cli("google.com");
  13542. cli.enable_server_certificate_verification(true);
  13543. cli.set_ca_cert_path("hello");
  13544. auto res = cli.Get("/");
  13545. ASSERT_TRUE(!res);
  13546. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13547. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13548. // should be set
  13549. EXPECT_EQ(0, res.ssl_error());
  13550. // Verify backend error is captured for SSLLoadingCerts
  13551. // This error occurs when loading CA certificates fails
  13552. EXPECT_NE(0UL, res.ssl_backend_error());
  13553. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13554. // OpenSSL specific error codes:
  13555. // > openssl errstr 0x80000002
  13556. // error:80000002:system library::No such file or directory
  13557. // > openssl errstr 0xA000126
  13558. // error:0A000126:SSL routines::unexpected eof while reading
  13559. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13560. res.ssl_backend_error() == 0xA000126);
  13561. #endif
  13562. }
  13563. TEST(SSLClientTest, ServerCertificateVerification4) {
  13564. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13565. ASSERT_TRUE(svr.is_valid());
  13566. svr.Get("/test", [&](const Request &, Response &res) {
  13567. res.set_content("test", "text/plain");
  13568. svr.stop();
  13569. ASSERT_TRUE(true);
  13570. });
  13571. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13572. auto se = detail::scope_exit([&] {
  13573. t.join();
  13574. ASSERT_FALSE(svr.is_running());
  13575. });
  13576. svr.wait_until_ready();
  13577. SSLClient cli("127.0.0.1", PORT);
  13578. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13579. cli.enable_server_certificate_verification(true);
  13580. cli.set_connection_timeout(30);
  13581. auto res = cli.Get("/test");
  13582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13583. ASSERT_EQ(StatusCode::OK_200, res->status);
  13584. }
  13585. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13586. std::string cert;
  13587. read_file(CA_CERT_FILE, cert);
  13588. SSLClient cli("google.com");
  13589. cli.load_ca_cert_store(cert.data(), cert.size());
  13590. const auto res = cli.Get("/");
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13593. }
  13594. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13595. // clang-format off
  13596. static constexpr char cert[] =
  13597. "GlobalSign Root CA\n"
  13598. "==================\n"
  13599. "-----BEGIN CERTIFICATE-----\n"
  13600. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13601. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13602. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13603. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13604. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13605. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13606. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13607. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13608. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13609. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13610. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13611. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13612. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13613. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13614. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13615. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13616. "-----END CERTIFICATE-----\n";
  13617. // clang-format on
  13618. SSLClient cli("google.com");
  13619. cli.load_ca_cert_store(cert, sizeof(cert));
  13620. const auto res = cli.Get("/");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13623. }
  13624. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13625. SSLClient cli("www.youtube.com");
  13626. cli.set_ca_cert_path(CA_CERT_FILE);
  13627. cli.enable_server_certificate_verification(true);
  13628. cli.set_follow_location(true);
  13629. auto res = cli.Get("/");
  13630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13631. ASSERT_EQ(StatusCode::OK_200, res->status);
  13632. }
  13633. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13634. SSLClient cli("wWw.YouTube.Com");
  13635. cli.set_ca_cert_path(CA_CERT_FILE);
  13636. cli.enable_server_certificate_verification(true);
  13637. cli.enable_server_hostname_verification(true);
  13638. cli.set_follow_location(true);
  13639. auto res = cli.Get("/");
  13640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13641. ASSERT_EQ(StatusCode::OK_200, res->status);
  13642. }
  13643. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13644. SSLClient cli("gOoGlE.COm");
  13645. cli.enable_server_certificate_verification(true);
  13646. cli.enable_server_hostname_verification(true);
  13647. cli.set_follow_location(true);
  13648. auto res = cli.Get("/");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. TEST(SSLClientTest, Issue2004_Online) {
  13653. Client client("https://google.com");
  13654. client.set_follow_location(true);
  13655. auto res = client.Get("/");
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. ASSERT_EQ(StatusCode::OK_200, res->status);
  13658. auto body = res->body;
  13659. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13660. }
  13661. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13662. // Create SSLClient with invalid cert/key to make is_valid() return false
  13663. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13664. "nonexistent_key.pem");
  13665. // is_valid() should be false due to cert loading failure
  13666. ASSERT_FALSE(cli.is_valid());
  13667. auto res = cli.Get("/");
  13668. ASSERT_FALSE(res);
  13669. EXPECT_EQ(Error::SSLConnection, res.error());
  13670. }
  13671. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13672. // Test for Issue #2251: SSL error not properly reported when client cert
  13673. // and key paths are swapped or mismatched
  13674. // This simulates the scenario where user accidentally swaps the cert and key
  13675. // files
  13676. // Using client cert file as private key and vice versa (completely wrong)
  13677. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13678. // Should fail validation due to cert/key mismatch
  13679. ASSERT_FALSE(cli.is_valid());
  13680. // Attempt to make a request should fail with proper error
  13681. auto res = cli.Get("/");
  13682. ASSERT_FALSE(res);
  13683. EXPECT_EQ(Error::SSLConnection, res.error());
  13684. // SSL error should be recorded in the Result object (this is the key fix for
  13685. // Issue #2251)
  13686. auto backend_error = res.ssl_backend_error();
  13687. EXPECT_NE(0u, backend_error);
  13688. }
  13689. // Tests cert/key mismatch detection at the TLS context level
  13690. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13691. // Test that using mismatched cert/key causes connection failure.
  13692. // We verify this at the SSLClient level rather than through internal
  13693. // TLS API functions.
  13694. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13695. cli.enable_server_certificate_verification(false);
  13696. cli.set_connection_timeout(2);
  13697. // The mismatch should cause a connection or handshake error
  13698. auto res = cli.Get("/test");
  13699. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13700. // Either way, the request should fail
  13701. EXPECT_FALSE(res);
  13702. }
  13703. #endif
  13704. #if 0
  13705. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13706. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13707. ASSERT_TRUE(cli != nullptr);
  13708. cli->set_address_family(AF_INET6);
  13709. cli->set_interface("en0");
  13710. auto res = cli->Get("/get");
  13711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13712. ASSERT_EQ(StatusCode::OK_200, res->status);
  13713. }
  13714. #endif
  13715. // Client certificate tests - work with all TLS backends
  13716. #ifdef CPPHTTPLIB_SSL_ENABLED
  13717. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13718. void ClientCertPresent(
  13719. const std::string &client_cert_file,
  13720. const std::string &client_private_key_file,
  13721. const std::string &client_encrypted_private_key_pass = std::string(),
  13722. const ClientCertServerSetup &setup = nullptr) {
  13723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13724. ASSERT_TRUE(svr.is_valid());
  13725. if (setup) { setup(svr); }
  13726. svr.Get("/test", [&](const Request &req, Response &res) {
  13727. res.set_content("test", "text/plain");
  13728. auto cert = req.peer_cert();
  13729. ASSERT_TRUE(static_cast<bool>(cert));
  13730. std::string common_name = cert.subject_cn();
  13731. EXPECT_EQ("Common Name", common_name);
  13732. });
  13733. auto port = svr.bind_to_any_port(HOST);
  13734. ASSERT_LT(0, port);
  13735. thread t = thread([&]() { svr.listen_after_bind(); });
  13736. auto se = detail::scope_exit([&] {
  13737. svr.stop();
  13738. t.join();
  13739. ASSERT_FALSE(svr.is_running());
  13740. });
  13741. svr.wait_until_ready();
  13742. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13743. client_encrypted_private_key_pass);
  13744. cli.enable_server_certificate_verification(false);
  13745. cli.set_connection_timeout(30);
  13746. auto res = cli.Get("/test");
  13747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13748. ASSERT_EQ(StatusCode::OK_200, res->status);
  13749. }
  13750. TEST(SSLClientServerTest, ClientCertPresent) {
  13751. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13752. }
  13753. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13754. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13755. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13756. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13757. }
  13758. // Expects svr, which must require client certificates, to reject a client
  13759. // that has none
  13760. void RejectsClientWithoutCert(SSLServer &svr) {
  13761. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13762. auto port = svr.bind_to_any_port(HOST);
  13763. ASSERT_LT(0, port);
  13764. thread t = thread([&]() { svr.listen_after_bind(); });
  13765. auto se = detail::scope_exit([&] {
  13766. svr.stop();
  13767. t.join();
  13768. ASSERT_FALSE(svr.is_running());
  13769. });
  13770. svr.wait_until_ready();
  13771. SSLClient cli(HOST, port);
  13772. cli.set_connection_timeout(30);
  13773. // Skip the server certificate check, so that the request fails because the
  13774. // client certificate is missing rather than because cert.pem is not trusted
  13775. cli.enable_server_certificate_verification(false);
  13776. auto res = cli.Get("/test");
  13777. ASSERT_FALSE(res);
  13778. // The server rejects the client during the handshake, or on TLS 1.3 right
  13779. // after it, which the client notices on its first write or read
  13780. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13781. res.error() == Error::Write || res.error() == Error::Read)
  13782. << to_string(res.error());
  13783. if (res.error() == Error::SSLConnection) {
  13784. EXPECT_NE(0UL, res.ssl_backend_error());
  13785. }
  13786. // A rejection noticed on the write keeps the TLS error the write hit
  13787. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13788. }
  13789. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13791. ASSERT_TRUE(svr.is_valid());
  13792. if (setup) { setup(svr); }
  13793. RejectsClientWithoutCert(svr);
  13794. }
  13795. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13796. // A server that requires client certificates must keep requiring them after
  13797. // setup changes it, and keep accepting a client that has one
  13798. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13799. ClientCertMissing(setup);
  13800. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13801. setup);
  13802. }
  13803. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13804. ClientCertStillRequired([](SSLServer &svr) {
  13805. ASSERT_TRUE(tls::set_verify_callback(
  13806. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13807. });
  13808. }
  13809. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13810. ClientCertStillRequired([](SSLServer &svr) {
  13811. ASSERT_TRUE(tls::set_verify_callback(
  13812. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13813. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13814. });
  13815. }
  13816. // The client verifies the server certificate during the handshake, so a
  13817. // server that fails the check never gets the client certificate, even when a
  13818. // verifier of the client's own accepts it
  13819. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13820. struct Case {
  13821. const char *trusted_ca;
  13822. const char *host;
  13823. Error error;
  13824. };
  13825. // cert2.pem names localhost: the first client does not trust it, and the
  13826. // second trusts it but asks for another name
  13827. for (const auto &c :
  13828. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13829. Case{SERVER_CERT2_FILE, "example.com",
  13830. Error::SSLServerHostnameVerification}}) {
  13831. for (auto with_verifier : {false, true}) {
  13832. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13833. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13834. CLIENT_CA_CERT_FILE);
  13835. ASSERT_TRUE(svr.is_valid());
  13836. std::atomic<bool> got_client_cert{false};
  13837. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13838. [&](const tls::VerifyContext &) {
  13839. got_client_cert = true;
  13840. return true;
  13841. }));
  13842. auto port = svr.bind_to_any_port("127.0.0.1");
  13843. ASSERT_LT(0, port);
  13844. thread t = thread([&] { svr.listen_after_bind(); });
  13845. svr.wait_until_ready();
  13846. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13847. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13848. cli.set_ca_cert_path(c.trusted_ca);
  13849. if (with_verifier) {
  13850. cli.set_server_certificate_verifier(
  13851. [](const tls::VerifyContext &) { return true; });
  13852. }
  13853. auto res = cli.Get("/");
  13854. EXPECT_FALSE(res);
  13855. EXPECT_EQ(c.error, res.error());
  13856. svr.stop();
  13857. t.join();
  13858. EXPECT_FALSE(got_client_cert);
  13859. }
  13860. }
  13861. }
  13862. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13863. std::string cert_pem, key_pem, ca_pem;
  13864. read_file(SERVER_CERT_FILE, cert_pem);
  13865. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13866. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13867. ASSERT_TRUE(
  13868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13869. }
  13870. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13872. ASSERT_TRUE(svr.is_valid());
  13873. UpdateCertsPemWithClientCA(svr);
  13874. RejectsClientWithoutCert(svr);
  13875. }
  13876. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13877. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13878. }
  13879. // A TLS error from one request must not show up in a later request's Result
  13880. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13882. ASSERT_TRUE(svr.is_valid());
  13883. svr.Get("/test", [](const Request &, Response &res) {
  13884. res.set_content("test", "text/plain");
  13885. });
  13886. auto port = svr.bind_to_any_port(HOST);
  13887. ASSERT_LT(0, port);
  13888. thread t = thread([&]() { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. });
  13894. svr.wait_until_ready();
  13895. SSLClient cli(HOST, port);
  13896. cli.set_connection_timeout(30);
  13897. cli.enable_server_hostname_verification(false);
  13898. // cert.pem is not trusted, so the handshake fails
  13899. ASSERT_FALSE(cli.Get("/test"));
  13900. cli.enable_server_certificate_verification(false);
  13901. auto res = cli.Get("/test");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(0, res.ssl_error());
  13904. EXPECT_EQ(0UL, res.ssl_backend_error());
  13905. }
  13906. // PEM memory-based constructor tests (works with all TLS backends).
  13907. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13908. // terminator after it.
  13909. void PemMemoryClientCertPresent(
  13910. const std::string &client_cert_file,
  13911. const std::string &client_private_key_file,
  13912. const std::string &client_encrypted_private_key_pass = std::string(),
  13913. bool exact_size = false) {
  13914. // Read PEM files into memory
  13915. std::string server_cert_pem, server_key_pem;
  13916. std::string client_ca_pem;
  13917. std::string client_cert_pem, client_key_pem;
  13918. read_file(SERVER_CERT_FILE, server_cert_pem);
  13919. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13920. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13921. read_file(client_cert_file, client_cert_pem);
  13922. read_file(client_private_key_file, client_key_pem);
  13923. std::list<std::vector<char>> exact_copies;
  13924. auto data = [&](const std::string &pem) -> const char * {
  13925. if (!exact_size) { return pem.c_str(); }
  13926. exact_copies.emplace_back(pem.begin(), pem.end());
  13927. return exact_copies.back().data();
  13928. };
  13929. // Create server with PEM memory
  13930. SSLServer::PemMemory server_pem = {
  13931. data(server_cert_pem),
  13932. server_cert_pem.size(),
  13933. data(server_key_pem),
  13934. server_key_pem.size(),
  13935. data(client_ca_pem),
  13936. client_ca_pem.size(),
  13937. nullptr // no password for server key
  13938. };
  13939. SSLServer svr(server_pem);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. svr.Get("/test", [&](const Request &req, Response &res) {
  13942. res.set_content("test", "text/plain");
  13943. auto cert = req.peer_cert();
  13944. ASSERT_TRUE(static_cast<bool>(cert));
  13945. EXPECT_EQ("Common Name", cert.subject_cn());
  13946. });
  13947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop();
  13950. t.join();
  13951. ASSERT_FALSE(svr.is_running());
  13952. });
  13953. svr.wait_until_ready();
  13954. // Create client with PEM memory
  13955. const char *password = client_encrypted_private_key_pass.empty()
  13956. ? nullptr
  13957. : client_encrypted_private_key_pass.c_str();
  13958. SSLClient::PemMemory client_pem = {
  13959. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13960. client_key_pem.size(), password};
  13961. SSLClient cli(HOST, PORT, client_pem);
  13962. cli.enable_server_certificate_verification(false);
  13963. cli.set_connection_timeout(30);
  13964. auto res = cli.Get("/test");
  13965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13966. ASSERT_EQ(StatusCode::OK_200, res->status);
  13967. }
  13968. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13969. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13970. }
  13971. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13972. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13973. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13974. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13975. }
  13976. // A server built from PEM memory with a client CA requires client certificates,
  13977. // also when the CA is a NUL-terminated string passed with a length of 0
  13978. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13979. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13980. read_file(SERVER_CERT_FILE, server_cert_pem);
  13981. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13982. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13983. SSLServer::PemMemory server_pem = {
  13984. server_cert_pem.c_str(),
  13985. server_cert_pem.size(),
  13986. server_key_pem.c_str(),
  13987. server_key_pem.size(),
  13988. client_ca_pem.c_str(),
  13989. client_ca_pem.size(),
  13990. nullptr // no password for server key
  13991. };
  13992. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13993. SCOPED_TRACE(client_ca_pem_len);
  13994. server_pem.client_ca_pem_len = client_ca_pem_len;
  13995. SSLServer svr(server_pem);
  13996. ASSERT_TRUE(svr.is_valid());
  13997. RejectsClientWithoutCert(svr);
  13998. }
  13999. // An empty CA fails to load instead of turning the check off
  14000. server_pem.client_ca_pem = "";
  14001. server_pem.client_ca_pem_len = 0;
  14002. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14003. }
  14004. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14005. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14006. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14007. true);
  14008. }
  14009. // A length shorter than the PEM cuts it short, so it no longer loads
  14010. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14011. std::string cert, key;
  14012. read_file(SERVER_CERT_FILE, cert);
  14013. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14014. for (auto cut_cert : {true, false}) {
  14015. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14016. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14017. SSLServer::PemMemory server_pem = {
  14018. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14019. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14020. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14021. key_len, nullptr};
  14022. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14023. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14024. key.c_str(), key_len, nullptr};
  14025. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14026. }
  14027. }
  14028. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14029. class NoListenSSLServer : public SSLServer {
  14030. public:
  14031. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14032. const char *client_ca_cert_file_path,
  14033. const char *client_ca_cert_dir_path = nullptr)
  14034. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14035. client_ca_cert_dir_path),
  14036. stop_(false) {}
  14037. std::atomic_bool stop_;
  14038. private:
  14039. bool process_and_close_socket(socket_t /*sock*/) override {
  14040. // Don't create SSL context
  14041. while (!stop_.load()) {
  14042. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14043. }
  14044. return true;
  14045. }
  14046. };
  14047. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14048. CLIENT_CA_CERT_FILE);
  14049. ASSERT_TRUE(svr.is_valid());
  14050. svr.Get("/test", [&](const Request &, Response &res) {
  14051. res.set_content("test", "text/plain");
  14052. });
  14053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14054. auto se = detail::scope_exit([&] {
  14055. svr.stop_ = true;
  14056. svr.stop();
  14057. t.join();
  14058. ASSERT_FALSE(svr.is_running());
  14059. });
  14060. svr.wait_until_ready();
  14061. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14062. cli.enable_server_certificate_verification(false);
  14063. cli.set_connection_timeout(1);
  14064. auto res = cli.Get("/test");
  14065. ASSERT_TRUE(!res);
  14066. EXPECT_EQ(Error::SSLConnection, res.error());
  14067. // Timeout results in WantRead error code (maps to backend-specific value)
  14068. EXPECT_NE(0, res.ssl_error());
  14069. }
  14070. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14071. // Test SSLServer with client certificate verification using the standard
  14072. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14074. CLIENT_CA_CERT_DIR);
  14075. ASSERT_TRUE(svr.is_valid());
  14076. svr.Get("/test", [&](const Request &req, Response &res) {
  14077. res.set_content("test", "text/plain");
  14078. auto cert = req.peer_cert();
  14079. ASSERT_TRUE(static_cast<bool>(cert));
  14080. auto common_name = cert.subject_cn();
  14081. EXPECT_EQ("Common Name", common_name);
  14082. });
  14083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14084. auto se = detail::scope_exit([&] {
  14085. svr.stop();
  14086. t.join();
  14087. ASSERT_FALSE(svr.is_running());
  14088. });
  14089. svr.wait_until_ready();
  14090. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14091. cli.enable_server_certificate_verification(false);
  14092. cli.set_connection_timeout(30);
  14093. auto res = cli.Get("/test");
  14094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14095. ASSERT_EQ(StatusCode::OK_200, res->status);
  14096. }
  14097. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14098. // Verifies that wildcard matching and exact matching work consistently
  14099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14100. using namespace httplib::tls;
  14101. // We need a running server to test against
  14102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14103. ASSERT_TRUE(svr.is_valid());
  14104. svr.Get("/test", [](const Request &, Response &res) {
  14105. res.set_content("ok", "text/plain");
  14106. });
  14107. thread t([&]() { svr.listen(HOST, PORT); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. });
  14112. svr.wait_until_ready();
  14113. bool verify_callback_called = false;
  14114. bool verify_result_wrong = false;
  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. // Note: Test certificate has CN="Common Name", not "localhost"
  14120. bool verify_result_cn = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. verify_callback_called = true;
  14123. if (!ctx.cert) return false;
  14124. // Test 1: "Common Name" should match (our test server cert CN)
  14125. verify_result_cn = ctx.check_hostname("Common Name");
  14126. // Test 2: wrong hostname should not match
  14127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14128. return true; // Accept for the purpose of this test
  14129. });
  14130. auto res = cli.Get("/test");
  14131. // The request may succeed or fail depending on cert configuration
  14132. // but the callback should have been called
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. // CN="Common Name" should match our test certificate
  14136. //
  14137. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14138. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14139. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14140. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14141. // <openssl/base.h>, which is included transitively when
  14142. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14143. #if defined(OPENSSL_IS_BORINGSSL)
  14144. EXPECT_FALSE(verify_result_cn)
  14145. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14146. #else
  14147. EXPECT_TRUE(verify_result_cn)
  14148. << "verify_hostname should match 'Common Name' (certificate CN)";
  14149. #endif
  14150. // Wrong hostname should not match
  14151. EXPECT_FALSE(verify_result_wrong)
  14152. << "verify_hostname should not match 'wronghost.example.com'";
  14153. }
  14154. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14155. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14156. // X509_check_ip behavior and must hold for every backend.
  14157. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14158. using namespace httplib::tls;
  14159. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14160. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14161. ASSERT_TRUE(svr.is_valid());
  14162. svr.Get("/test", [](const Request &, Response &res) {
  14163. res.set_content("ok", "text/plain");
  14164. });
  14165. thread t([&]() { svr.listen(HOST, PORT); });
  14166. auto se = detail::scope_exit([&] {
  14167. svr.stop();
  14168. t.join();
  14169. });
  14170. svr.wait_until_ready();
  14171. bool verify_callback_called = false;
  14172. bool ip_matched_via_cn = true;
  14173. SSLClient cli(HOST, PORT);
  14174. cli.enable_server_certificate_verification(true);
  14175. cli.set_ca_cert_path(CA_CERT_FILE);
  14176. cli.set_connection_timeout(5);
  14177. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14178. verify_callback_called = true;
  14179. if (!ctx.cert) return false;
  14180. // The IP appears only in the CN, so it must NOT be accepted.
  14181. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14182. return true; // Accept for the purpose of this test
  14183. });
  14184. cli.Get("/test");
  14185. ASSERT_TRUE(verify_callback_called)
  14186. << "Verify callback should have been called";
  14187. EXPECT_FALSE(ip_matched_via_cn)
  14188. << "An IP host must not be authenticated via the certificate CN";
  14189. }
  14190. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14191. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14192. using namespace httplib::tls;
  14193. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14194. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14195. ASSERT_TRUE(svr.is_valid());
  14196. svr.Get("/test", [](const Request &, Response &res) {
  14197. res.set_content("ok", "text/plain");
  14198. });
  14199. thread t([&]() { svr.listen(HOST, PORT); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. });
  14204. svr.wait_until_ready();
  14205. bool verify_callback_called = false;
  14206. bool san_matched = false;
  14207. bool wrong_ipv6_matched = true;
  14208. bool cn_ipv6_matched = true;
  14209. SSLClient cli(HOST, PORT);
  14210. cli.enable_server_certificate_verification(true);
  14211. cli.set_ca_cert_path(CA_CERT_FILE);
  14212. cli.set_connection_timeout(5);
  14213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14214. verify_callback_called = true;
  14215. if (!ctx.cert) return false;
  14216. // Matches the IPv6 iPAddress SAN.
  14217. san_matched = ctx.check_hostname("2001:db8::1");
  14218. // A different IPv6 address must not match.
  14219. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14220. // "::1" lives only in the CN, so it must not be accepted.
  14221. cn_ipv6_matched = ctx.check_hostname("::1");
  14222. return true; // Accept for the purpose of this test
  14223. });
  14224. cli.Get("/test");
  14225. ASSERT_TRUE(verify_callback_called)
  14226. << "Verify callback should have been called";
  14227. EXPECT_TRUE(san_matched)
  14228. << "verify_hostname should match an IPv6 iPAddress SAN";
  14229. EXPECT_FALSE(wrong_ipv6_matched)
  14230. << "verify_hostname should not match a non-matching IPv6 address";
  14231. EXPECT_FALSE(cn_ipv6_matched)
  14232. << "An IPv6 host must not be authenticated via the certificate CN";
  14233. }
  14234. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14235. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14236. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14237. using namespace httplib::tls;
  14238. // SANs: DNS:a.zz, IP:42.46.122.122
  14239. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14240. ASSERT_TRUE(svr.is_valid());
  14241. svr.Get("/test", [](const Request &, Response &res) {
  14242. res.set_content("ok", "text/plain");
  14243. });
  14244. auto port = svr.bind_to_any_port(HOST);
  14245. thread t([&]() { svr.listen_after_bind(); });
  14246. auto se = detail::scope_exit([&] {
  14247. svr.stop();
  14248. t.join();
  14249. });
  14250. svr.wait_until_ready();
  14251. bool verify_callback_called = false;
  14252. bool dns_san_matched = false;
  14253. bool ip_san_matched = false;
  14254. bool ip_matched_via_dns_san = true;
  14255. bool dns_matched_via_ip_san = true;
  14256. bool cn_matched_next_to_dns_san = true;
  14257. SSLClient cli(HOST, port);
  14258. cli.enable_server_certificate_verification(true);
  14259. cli.set_ca_cert_path(CA_CERT_FILE);
  14260. cli.set_connection_timeout(5);
  14261. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14262. verify_callback_called = true;
  14263. if (!ctx.cert) return false;
  14264. dns_san_matched = ctx.check_hostname("a.zz");
  14265. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14266. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14267. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14268. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14269. return true; // Accept for the purpose of this test
  14270. });
  14271. cli.Get("/test");
  14272. ASSERT_TRUE(verify_callback_called)
  14273. << "Verify callback should have been called";
  14274. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14275. EXPECT_TRUE(ip_san_matched)
  14276. << "verify_hostname should match an iPAddress SAN";
  14277. EXPECT_FALSE(ip_matched_via_dns_san)
  14278. << "An IP host must not be authenticated via a dNSName SAN";
  14279. EXPECT_FALSE(dns_matched_via_ip_san)
  14280. << "A DNS host must not be authenticated via an iPAddress SAN";
  14281. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14282. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14283. }
  14284. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14285. // "www.*.example.test" names one host and not every host under example.test.
  14286. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14287. using namespace httplib::tls;
  14288. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14289. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14290. ASSERT_TRUE(svr.is_valid());
  14291. svr.Get("/test", [](const Request &, Response &res) {
  14292. res.set_content("ok", "text/plain");
  14293. });
  14294. auto port = svr.bind_to_any_port(HOST);
  14295. thread t([&]() { svr.listen_after_bind(); });
  14296. auto se = detail::scope_exit([&] {
  14297. svr.stop();
  14298. t.join();
  14299. });
  14300. svr.wait_until_ready();
  14301. bool verify_callback_called = false;
  14302. bool leftmost_wildcard_matched = false;
  14303. bool wildcard_spanned_labels = true;
  14304. bool inner_wildcard_matched = true;
  14305. SSLClient cli(HOST, port);
  14306. cli.enable_server_certificate_verification(true);
  14307. cli.set_ca_cert_path(CA_CERT_FILE);
  14308. cli.set_connection_timeout(5);
  14309. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14310. verify_callback_called = true;
  14311. if (!ctx.cert) return false;
  14312. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14313. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14314. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14315. return true; // Accept for the purpose of this test
  14316. });
  14317. cli.Get("/test");
  14318. ASSERT_TRUE(verify_callback_called)
  14319. << "Verify callback should have been called";
  14320. EXPECT_TRUE(leftmost_wildcard_matched)
  14321. << "A leftmost wildcard should match a single label";
  14322. EXPECT_FALSE(wildcard_spanned_labels)
  14323. << "A wildcard label must not match more than one label";
  14324. EXPECT_FALSE(inner_wildcard_matched)
  14325. << "A wildcard outside the leftmost label must not be honoured";
  14326. }
  14327. // sans() must report each SAN entry under its own type.
  14328. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14329. using namespace httplib::tls;
  14330. // SANs: DNS:a.zz, IP:42.46.122.122
  14331. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14332. ASSERT_TRUE(svr.is_valid());
  14333. svr.Get("/test", [](const Request &, Response &res) {
  14334. res.set_content("ok", "text/plain");
  14335. });
  14336. auto port = svr.bind_to_any_port(HOST);
  14337. thread t([&]() { svr.listen_after_bind(); });
  14338. auto se = detail::scope_exit([&] {
  14339. svr.stop();
  14340. t.join();
  14341. });
  14342. svr.wait_until_ready();
  14343. bool verify_callback_called = false;
  14344. std::vector<SanEntry> sans;
  14345. SSLClient cli(HOST, port);
  14346. cli.enable_server_certificate_verification(true);
  14347. cli.set_ca_cert_path(CA_CERT_FILE);
  14348. cli.set_connection_timeout(5);
  14349. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14350. verify_callback_called = true;
  14351. if (!ctx.cert) return false;
  14352. sans = ctx.sans();
  14353. return true; // Accept for the purpose of this test
  14354. });
  14355. cli.Get("/test");
  14356. ASSERT_TRUE(verify_callback_called)
  14357. << "Verify callback should have been called";
  14358. auto has_san = [&](SanType type, const std::string &value) {
  14359. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14360. return san.type == type && san.value == value;
  14361. });
  14362. };
  14363. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14364. << "sans() should report the dNSName SAN";
  14365. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14366. << "sans() should report the iPAddress SAN";
  14367. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14368. << "sans() must not report the dNSName SAN as an address";
  14369. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14370. << "sans() must not report the iPAddress SAN as a DNS name";
  14371. }
  14372. #endif
  14373. // mbedTLS-specific callback constructor test
  14374. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14375. #ifdef CPPHTTPLIB_SSL_ENABLED
  14376. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14378. ASSERT_TRUE(svr.is_valid());
  14379. // Set up a handler to verify client certificate is present
  14380. bool client_cert_verified = false;
  14381. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14382. // Verify that client certificate was provided
  14383. client_cert_verified = true;
  14384. res.set_content("success", "text/plain");
  14385. });
  14386. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. t.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. });
  14392. svr.wait_until_ready();
  14393. // Client with certificate
  14394. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14395. cli.enable_server_certificate_verification(false);
  14396. cli.set_connection_timeout(30);
  14397. auto res = cli.Get("/test");
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. ASSERT_EQ(StatusCode::OK_200, res->status);
  14400. ASSERT_TRUE(client_cert_verified);
  14401. EXPECT_EQ("success", res->body);
  14402. }
  14403. #endif
  14404. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14405. // backends
  14406. #ifdef CPPHTTPLIB_SSL_ENABLED
  14407. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14408. using namespace httplib::tls;
  14409. // Test that when client CA cert file is provided,
  14410. // the server properly requests and validates client certificates
  14411. // Create a server with client authentication
  14412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14413. ASSERT_TRUE(svr.is_valid());
  14414. bool handler_called = false;
  14415. svr.Get("/test", [&](const Request &req, Response &res) {
  14416. handler_called = true;
  14417. // Verify that a client certificate was provided
  14418. auto cert = req.peer_cert();
  14419. ASSERT_TRUE(static_cast<bool>(cert));
  14420. // Get the issuer name
  14421. std::string issuer_str = cert.issuer_name();
  14422. ASSERT_FALSE(issuer_str.empty());
  14423. // The client certificate should be issued by our test CA
  14424. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14425. res.set_content("authenticated", "text/plain");
  14426. });
  14427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14428. auto se = detail::scope_exit([&] {
  14429. svr.stop();
  14430. t.join();
  14431. ASSERT_FALSE(svr.is_running());
  14432. });
  14433. svr.wait_until_ready();
  14434. // Connect with a client certificate issued by the CA
  14435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14436. cli.enable_server_certificate_verification(false);
  14437. cli.set_connection_timeout(30);
  14438. auto res = cli.Get("/test");
  14439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14440. ASSERT_EQ(StatusCode::OK_200, res->status);
  14441. ASSERT_TRUE(handler_called);
  14442. EXPECT_EQ("authenticated", res->body);
  14443. }
  14444. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14445. using namespace httplib::tls;
  14446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14447. ASSERT_TRUE(svr.is_valid());
  14448. svr.Get("/test", [](const Request &, Response &res) {
  14449. res.set_content("ok", "text/plain");
  14450. });
  14451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14452. auto se = detail::scope_exit([&] {
  14453. svr.stop();
  14454. t.join();
  14455. });
  14456. svr.wait_until_ready();
  14457. SSLClient cli(HOST, PORT);
  14458. cli.enable_server_certificate_verification(false);
  14459. cli.set_connection_timeout(30);
  14460. bool cert_checked = false;
  14461. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14462. if (ctx.cert) {
  14463. auto sans = ctx.sans();
  14464. // Test certificate may or may not have SANs - just verify the API
  14465. // works If SANs exist, verify the types are valid
  14466. for (const auto &san : sans) {
  14467. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14468. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14469. san.type == SanType::OTHER);
  14470. EXPECT_FALSE(san.value.empty());
  14471. }
  14472. cert_checked = true;
  14473. }
  14474. return true;
  14475. });
  14476. auto res = cli.Get("/test");
  14477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14478. EXPECT_TRUE(cert_checked);
  14479. }
  14480. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14481. using namespace httplib::tls;
  14482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14483. ASSERT_TRUE(svr.is_valid());
  14484. svr.Get("/test", [](const Request &, Response &res) {
  14485. res.set_content("ok", "text/plain");
  14486. });
  14487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14488. auto se = detail::scope_exit([&] {
  14489. svr.stop();
  14490. t.join();
  14491. });
  14492. svr.wait_until_ready();
  14493. SSLClient cli(HOST, PORT);
  14494. cli.enable_server_certificate_verification(false);
  14495. cli.set_connection_timeout(30);
  14496. bool validity_checked = false;
  14497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14498. if (ctx.cert) {
  14499. time_t not_before = 0, not_after = 0;
  14500. bool result = ctx.validity(not_before, not_after);
  14501. EXPECT_TRUE(result);
  14502. // Verify that not_before < now < not_after for a valid cert
  14503. time_t now = time(nullptr);
  14504. EXPECT_LT(not_before, now);
  14505. EXPECT_GT(not_after, now);
  14506. validity_checked = true;
  14507. }
  14508. return true;
  14509. });
  14510. auto res = cli.Get("/test");
  14511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14512. EXPECT_TRUE(validity_checked);
  14513. }
  14514. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14515. using namespace httplib::tls;
  14516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14517. ASSERT_TRUE(svr.is_valid());
  14518. svr.Get("/test", [](const Request &, Response &res) {
  14519. res.set_content("ok", "text/plain");
  14520. });
  14521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. });
  14526. svr.wait_until_ready();
  14527. SSLClient cli(HOST, PORT);
  14528. cli.enable_server_certificate_verification(false);
  14529. cli.set_connection_timeout(30);
  14530. bool serial_checked = false;
  14531. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14532. if (ctx.cert) {
  14533. std::string serial = ctx.serial();
  14534. EXPECT_FALSE(serial.empty());
  14535. // Serial should be a hex string
  14536. for (char c : serial) {
  14537. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14538. (c >= 'a' && c <= 'f'));
  14539. }
  14540. serial_checked = true;
  14541. }
  14542. return true;
  14543. });
  14544. auto res = cli.Get("/test");
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. EXPECT_TRUE(serial_checked);
  14547. }
  14548. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14549. // Test 1: Valid CA file - no error should be recorded
  14550. {
  14551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14552. CLIENT_CA_CERT_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. // With valid setup, last_ssl_error should be 0
  14555. EXPECT_EQ(0, svr.ssl_last_error());
  14556. }
  14557. // Test 2: Invalid CA file content
  14558. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14559. {
  14560. // Create a temporary file with completely invalid content
  14561. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14562. {
  14563. std::ofstream ofs(temp_invalid_ca);
  14564. ofs << "This is not a certificate file at all\n";
  14565. ofs << "Just plain text content\n";
  14566. }
  14567. // Create server with invalid CA file
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14569. // Clean up temporary file
  14570. std::remove(temp_invalid_ca);
  14571. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14572. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14573. // Note: SSL_CTX_load_verify_locations typically fails first,
  14574. // but our error handling code path is still exercised
  14575. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14576. }
  14577. }
  14578. TEST(VerifyCallbackTest, VerifyContextFields) {
  14579. using namespace httplib::tls;
  14580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14581. ASSERT_TRUE(svr.is_valid());
  14582. svr.Get("/test", [](const Request &, Response &res) {
  14583. res.set_content("ok", "text/plain");
  14584. });
  14585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. });
  14590. svr.wait_until_ready();
  14591. SSLClient cli(HOST, PORT);
  14592. cli.enable_server_certificate_verification(false);
  14593. cli.set_connection_timeout(30);
  14594. int callback_count = 0;
  14595. bool saw_leaf_cert = false;
  14596. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14597. if (ctx.cert) {
  14598. callback_count++;
  14599. // We should see at least one certificate (the leaf)
  14600. std::string cn = ctx.subject_cn();
  14601. if (!cn.empty()) { saw_leaf_cert = true; }
  14602. // Verify context fields are populated
  14603. EXPECT_NE(ctx.session, nullptr);
  14604. EXPECT_GE(ctx.depth, 0);
  14605. }
  14606. return true;
  14607. });
  14608. auto res = cli.Get("/test");
  14609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14610. EXPECT_GT(callback_count, 0);
  14611. EXPECT_TRUE(saw_leaf_cert);
  14612. }
  14613. // A verifier that accepts runs alongside the built-in verification, and is the
  14614. // only check once that is turned off.
  14615. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14616. using namespace httplib::tls;
  14617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14618. ASSERT_TRUE(svr.is_valid());
  14619. svr.Get("/test", [](const Request &, Response &res) {
  14620. res.set_content("ok", "text/plain");
  14621. });
  14622. auto port = svr.bind_to_any_port(HOST);
  14623. thread t([&]() { svr.listen_after_bind(); });
  14624. auto se = detail::scope_exit([&] {
  14625. svr.stop();
  14626. t.join();
  14627. });
  14628. svr.wait_until_ready();
  14629. SSLClient cli(HOST, port);
  14630. cli.enable_server_hostname_verification(false);
  14631. auto calls = 0;
  14632. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14633. calls++;
  14634. return true;
  14635. });
  14636. // cert.pem is not trusted
  14637. auto res = cli.Get("/test");
  14638. ASSERT_FALSE(res);
  14639. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14640. EXPECT_GT(calls, 0);
  14641. cli.enable_server_certificate_verification(false);
  14642. res = cli.Get("/test");
  14643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14644. EXPECT_EQ("ok", res->body);
  14645. }
  14646. // A verifier belongs to the client that set it, not to the thread that set it.
  14647. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14648. using namespace httplib::tls;
  14649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14650. ASSERT_TRUE(svr.is_valid());
  14651. svr.Get("/test", [](const Request &, Response &res) {
  14652. res.set_content("ok", "text/plain");
  14653. });
  14654. auto port = svr.bind_to_any_port(HOST);
  14655. thread t([&]() { svr.listen_after_bind(); });
  14656. auto se = detail::scope_exit([&] {
  14657. svr.stop();
  14658. t.join();
  14659. });
  14660. svr.wait_until_ready();
  14661. auto rejecting_calls = 0;
  14662. SSLClient rejecting(HOST, port);
  14663. rejecting.enable_server_certificate_verification(false);
  14664. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14665. rejecting_calls++;
  14666. return false;
  14667. });
  14668. auto accepting_calls = 0;
  14669. SSLClient accepting(HOST, port);
  14670. accepting.enable_server_certificate_verification(false);
  14671. // Set on another thread than the requests below.
  14672. thread([&]() {
  14673. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14674. accepting_calls++;
  14675. return true;
  14676. });
  14677. }).join();
  14678. // Requested on another thread than the verifier was set on.
  14679. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14680. EXPECT_GT(rejecting_calls, 0);
  14681. auto res = accepting.Get("/test");
  14682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14683. EXPECT_GT(accepting_calls, 0);
  14684. }
  14685. // A verifier replaced while a handshake runs it lives until it returns.
  14686. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14687. using namespace httplib::tls;
  14688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14689. ASSERT_TRUE(svr.is_valid());
  14690. svr.Get("/test", [](const Request &, Response &res) {
  14691. res.set_content("ok", "text/plain");
  14692. });
  14693. auto port = svr.bind_to_any_port(HOST);
  14694. thread t([&]() { svr.listen_after_bind(); });
  14695. auto se = detail::scope_exit([&] {
  14696. svr.stop();
  14697. t.join();
  14698. });
  14699. svr.wait_until_ready();
  14700. SSLClient cli(HOST, port);
  14701. cli.enable_server_certificate_verification(false);
  14702. std::promise<void> entered;
  14703. std::promise<void> replaced;
  14704. auto replaced_future = replaced.get_future();
  14705. auto first_call = true;
  14706. // Long enough to live on the heap
  14707. std::string expected(64, 'v');
  14708. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14709. if (first_call) {
  14710. first_call = false;
  14711. entered.set_value();
  14712. replaced_future.wait();
  14713. }
  14714. return expected == std::string(64, 'v');
  14715. });
  14716. thread request([&]() {
  14717. auto res = cli.Get("/test");
  14718. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14719. });
  14720. entered.get_future().wait();
  14721. cli.set_server_certificate_verifier(
  14722. [](const VerifyContext &) { return true; });
  14723. replaced.set_value();
  14724. request.join();
  14725. }
  14726. // VerifyContext::session is the same handle the other tls:: functions take.
  14727. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14728. using namespace httplib::tls;
  14729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14730. ASSERT_TRUE(svr.is_valid());
  14731. svr.Get("/test", [](const Request &, Response &res) {
  14732. res.set_content("ok", "text/plain");
  14733. });
  14734. auto port = svr.bind_to_any_port(HOST);
  14735. thread t([&]() { svr.listen_after_bind(); });
  14736. auto se = detail::scope_exit([&] {
  14737. svr.stop();
  14738. t.join();
  14739. });
  14740. svr.wait_until_ready();
  14741. SSLClient cli(HOST, port);
  14742. cli.enable_server_certificate_verification(false);
  14743. session_t verifier_session = nullptr;
  14744. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14745. verifier_session = ctx.session;
  14746. return true;
  14747. });
  14748. session_t session_verifier_session = nullptr;
  14749. cli.set_session_verifier([&](session_t session) {
  14750. session_verifier_session = session;
  14751. return SSLVerifierResponse::NoDecisionMade;
  14752. });
  14753. auto res = cli.Get("/test");
  14754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14755. EXPECT_NE(nullptr, verifier_session);
  14756. EXPECT_EQ(session_verifier_session, verifier_session);
  14757. }
  14758. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14759. using httplib::tls::TlsError;
  14760. // Test that verify_error_to_string returns empty for success
  14761. std::string success_str = TlsError::verify_error_to_string(0);
  14762. EXPECT_TRUE(success_str.empty());
  14763. // Test that verify_error_to_string returns non-empty for error codes
  14764. // Using a common error code (certificate expired)
  14765. std::string error_str =
  14766. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14767. EXPECT_FALSE(error_str.empty());
  14768. }
  14769. TEST(SessionVerifierTest, CertificateAccepted) {
  14770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14771. ASSERT_TRUE(svr.is_valid());
  14772. svr.Get("/test", [](const Request &, Response &res) {
  14773. res.set_content("ok", "text/plain");
  14774. });
  14775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14776. auto se = detail::scope_exit([&] {
  14777. svr.stop();
  14778. t.join();
  14779. });
  14780. svr.wait_until_ready();
  14781. SSLClient cli(HOST, PORT);
  14782. cli.enable_server_certificate_verification(false);
  14783. cli.set_connection_timeout(30);
  14784. bool callback_called = false;
  14785. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14786. EXPECT_NE(session, nullptr);
  14787. callback_called = true;
  14788. return SSLVerifierResponse::CertificateAccepted;
  14789. });
  14790. auto res = cli.Get("/test");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. EXPECT_EQ(200, res->status);
  14793. EXPECT_TRUE(callback_called);
  14794. }
  14795. TEST(SessionVerifierTest, CertificateRejected) {
  14796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14797. ASSERT_TRUE(svr.is_valid());
  14798. svr.Get("/test", [](const Request &, Response &res) {
  14799. res.set_content("ok", "text/plain");
  14800. });
  14801. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14802. auto se = detail::scope_exit([&] {
  14803. svr.stop();
  14804. t.join();
  14805. });
  14806. svr.wait_until_ready();
  14807. SSLClient cli(HOST, PORT);
  14808. cli.enable_server_certificate_verification(false);
  14809. cli.set_connection_timeout(30);
  14810. bool callback_called = false;
  14811. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14812. EXPECT_NE(session, nullptr);
  14813. callback_called = true;
  14814. return SSLVerifierResponse::CertificateRejected;
  14815. });
  14816. auto res = cli.Get("/test");
  14817. EXPECT_FALSE(res);
  14818. EXPECT_TRUE(callback_called);
  14819. }
  14820. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14822. ASSERT_TRUE(svr.is_valid());
  14823. svr.Get("/test", [](const Request &, Response &res) {
  14824. res.set_content("ok", "text/plain");
  14825. });
  14826. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14827. auto se = detail::scope_exit([&] {
  14828. svr.stop();
  14829. t.join();
  14830. });
  14831. svr.wait_until_ready();
  14832. // NoDecisionMade with verification disabled should succeed (no default check)
  14833. SSLClient cli(HOST, PORT);
  14834. cli.enable_server_certificate_verification(false);
  14835. cli.set_connection_timeout(30);
  14836. bool callback_called = false;
  14837. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14838. EXPECT_NE(session, nullptr);
  14839. callback_called = true;
  14840. return SSLVerifierResponse::NoDecisionMade;
  14841. });
  14842. auto res = cli.Get("/test");
  14843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14844. EXPECT_EQ(200, res->status);
  14845. EXPECT_TRUE(callback_called);
  14846. }
  14847. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14849. ASSERT_TRUE(svr.is_valid());
  14850. svr.Get("/test", [](const Request &, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. });
  14858. svr.wait_until_ready();
  14859. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14860. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14861. // so we only check that the request fails, not whether the callback was
  14862. // called.
  14863. SSLClient cli(HOST, PORT);
  14864. cli.enable_server_certificate_verification(true);
  14865. cli.set_connection_timeout(30);
  14866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14867. EXPECT_NE(session, nullptr);
  14868. return SSLVerifierResponse::NoDecisionMade;
  14869. });
  14870. auto res = cli.Get("/test");
  14871. EXPECT_FALSE(res);
  14872. }
  14873. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14874. // Test SSL server using PemMemory constructor with client CA certificates
  14875. // Read PEM files
  14876. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14877. read_file(SERVER_CERT_FILE, server_cert_pem);
  14878. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14879. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14880. // Create SSLServer with PemMemory constructor including client CA
  14881. SSLServer::PemMemory server_pem = {
  14882. server_cert_pem.c_str(),
  14883. server_cert_pem.size(),
  14884. server_key_pem.c_str(),
  14885. server_key_pem.size(),
  14886. client_ca_pem.c_str(),
  14887. client_ca_pem.size(),
  14888. nullptr // no password for server key
  14889. };
  14890. SSLServer svr(server_pem);
  14891. ASSERT_TRUE(svr.is_valid());
  14892. // No SSL error should be recorded for valid setup
  14893. EXPECT_EQ(0, svr.ssl_last_error());
  14894. // Set up server endpoints
  14895. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14896. res.set_content("ok", "text/plain");
  14897. });
  14898. // Start server in a thread
  14899. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14900. svr.wait_until_ready();
  14901. // Connect with client certificate (using constructor with paths)
  14902. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14903. cli.enable_server_certificate_verification(false);
  14904. auto res = cli.Get("/test-pem-ca");
  14905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14906. EXPECT_EQ(200, res->status);
  14907. EXPECT_EQ("ok", res->body);
  14908. svr.stop();
  14909. server_thread.join();
  14910. }
  14911. #endif
  14912. #ifdef _WIN32
  14913. TEST(CleanupTest, WSACleanup) {
  14914. int ret = WSACleanup();
  14915. ASSERT_EQ(0, ret);
  14916. }
  14917. #endif
  14918. #ifndef CPPHTTPLIB_SSL_ENABLED
  14919. TEST(NoSSLSupport, SimpleInterface) {
  14920. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14921. }
  14922. #endif
  14923. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14924. TEST(InvalidScheme, SimpleInterface) {
  14925. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14926. }
  14927. #endif
  14928. TEST(NoScheme, SimpleInterface) {
  14929. Client cli("yahoo.com:80");
  14930. ASSERT_TRUE(cli.is_valid());
  14931. }
  14932. TEST(SendAPI, SimpleInterface_Online) {
  14933. Client cli("http://yahoo.com");
  14934. Request req;
  14935. req.method = "GET";
  14936. req.path = "/";
  14937. auto res = cli.send(req);
  14938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14939. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14940. }
  14941. TEST(SendAPI, WithParamsInRequest) {
  14942. Server svr;
  14943. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14944. EXPECT_TRUE(req.has_param("test"));
  14945. EXPECT_EQ("test_value", req.get_param_value("test"));
  14946. });
  14947. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14948. auto se = detail::scope_exit([&] {
  14949. svr.stop();
  14950. t.join();
  14951. ASSERT_FALSE(svr.is_running());
  14952. });
  14953. svr.wait_until_ready();
  14954. Client cli(HOST, PORT);
  14955. {
  14956. Request req;
  14957. req.method = "GET";
  14958. req.path = "/";
  14959. req.params.emplace("test", "test_value");
  14960. auto res = cli.send(req);
  14961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14962. }
  14963. {
  14964. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. }
  14967. }
  14968. TEST(ClientImplMethods, GetSocketTest) {
  14969. httplib::Server svr;
  14970. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14971. res.status = StatusCode::OK_200;
  14972. });
  14973. auto port = svr.bind_to_any_port("127.0.0.1");
  14974. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14975. auto se = detail::scope_exit([&] {
  14976. svr.stop();
  14977. thread.join();
  14978. ASSERT_FALSE(svr.is_running());
  14979. });
  14980. svr.wait_until_ready();
  14981. {
  14982. httplib::Client cli("127.0.0.1", port);
  14983. cli.set_keep_alive(true);
  14984. // Use the behavior of cpp-httplib of opening the connection
  14985. // only when the first request happens. If that changes,
  14986. // this test would be obsolete.
  14987. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14988. // This also implicitly tests the server. But other tests would fail much
  14989. // earlier than this one to be considered.
  14990. auto res = cli.Get("/");
  14991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14992. EXPECT_EQ(StatusCode::OK_200, res->status);
  14993. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14994. }
  14995. }
  14996. #ifdef CPPHTTPLIB_SSL_ENABLED
  14997. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14998. Client cli("http://yahoo.com");
  14999. auto res = cli.Get("/");
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15002. cli.set_follow_location(true);
  15003. res = cli.Get("/");
  15004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15005. EXPECT_EQ(StatusCode::OK_200, res->status);
  15006. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15007. }
  15008. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15009. Client cli("https://yahoo.com");
  15010. auto res = cli.Get("/");
  15011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15013. cli.set_follow_location(true);
  15014. res = cli.Get("/");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15018. }
  15019. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15020. Client cli("https://yahoo.com");
  15021. auto res = cli.Get("/");
  15022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15023. ASSERT_FALSE(!res);
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. ASSERT_FALSE(res == nullptr);
  15026. ASSERT_TRUE(res != nullptr);
  15027. EXPECT_EQ(Error::Success, res.error());
  15028. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15029. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15030. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15031. cli.set_follow_location(true);
  15032. res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. EXPECT_EQ(Error::Success, res.error());
  15035. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15036. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15037. EXPECT_EQ(StatusCode::OK_200, res->status);
  15038. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15039. }
  15040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15041. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15042. Client cli("https://cdnjs.cloudflare.com");
  15043. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15044. Headers{{"Accept-Encoding", "br"}});
  15045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15046. EXPECT_EQ(StatusCode::OK_200, res->status);
  15047. EXPECT_EQ(287630U, res->body.size());
  15048. EXPECT_EQ("application/javascript; charset=utf-8",
  15049. res->get_header_value("Content-Type"));
  15050. }
  15051. #endif
  15052. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15053. #undef REDIR_HOST // Silence compiler warning
  15054. #define REDIR_HOST "https://httpbingo.org"
  15055. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15056. Client cli(REDIR_HOST);
  15057. cli.set_follow_location(true);
  15058. auto res =
  15059. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15061. EXPECT_EQ(StatusCode::OK_200, res->status);
  15062. }
  15063. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15064. Client cli(REDIR_HOST);
  15065. cli.set_follow_location(true);
  15066. Params params;
  15067. params.emplace("url", "http://example.com");
  15068. params.emplace("status_code", "302");
  15069. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15071. EXPECT_EQ(StatusCode::OK_200, res->status);
  15072. }
  15073. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15074. Client cli(REDIR_HOST);
  15075. cli.set_follow_location(true);
  15076. Params params;
  15077. params.emplace("url", "http://example.com");
  15078. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15080. EXPECT_EQ(StatusCode::OK_200, res->status);
  15081. }
  15082. TEST(HttpToHttpsRedirectTest, CertFile) {
  15083. auto ssl_port = PORT + 1;
  15084. Server svr;
  15085. ASSERT_TRUE(svr.is_valid());
  15086. svr.Get("/index", [&](const Request &, Response &res) {
  15087. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15088. "/index");
  15089. svr.stop();
  15090. });
  15091. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15092. ASSERT_TRUE(ssl_svr.is_valid());
  15093. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15094. res.set_content("test", "text/plain");
  15095. ssl_svr.stop();
  15096. });
  15097. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15098. thread t2 =
  15099. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15100. auto se = detail::scope_exit([&] {
  15101. t2.join();
  15102. t.join();
  15103. ASSERT_FALSE(svr.is_running());
  15104. });
  15105. svr.wait_until_ready();
  15106. ssl_svr.wait_until_ready();
  15107. Client cli("127.0.0.1", PORT);
  15108. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15109. cli.enable_server_certificate_verification(true);
  15110. cli.set_follow_location(true);
  15111. cli.set_connection_timeout(30);
  15112. auto res = cli.Get("/index");
  15113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15114. ASSERT_EQ(StatusCode::OK_200, res->status);
  15115. }
  15116. TEST(SSLClientRedirectTest, CertFile) {
  15117. auto ssl_port = PORT + 1;
  15118. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15119. ASSERT_TRUE(ssl_svr1.is_valid());
  15120. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15121. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15122. "/index");
  15123. ssl_svr1.stop();
  15124. });
  15125. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15126. ASSERT_TRUE(ssl_svr2.is_valid());
  15127. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15128. res.set_content("test", "text/plain");
  15129. ssl_svr2.stop();
  15130. });
  15131. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15132. thread t2 =
  15133. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15134. auto se = detail::scope_exit([&] {
  15135. t2.join();
  15136. t.join();
  15137. ASSERT_FALSE(ssl_svr1.is_running());
  15138. });
  15139. ssl_svr1.wait_until_ready();
  15140. ssl_svr2.wait_until_ready();
  15141. SSLClient cli("127.0.0.1", PORT);
  15142. std::string cert;
  15143. read_file(SERVER_CERT2_FILE, cert);
  15144. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15145. cli.enable_server_certificate_verification(true);
  15146. cli.set_follow_location(true);
  15147. cli.set_connection_timeout(30);
  15148. auto res = cli.Get("/index");
  15149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15150. ASSERT_EQ(StatusCode::OK_200, res->status);
  15151. }
  15152. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15153. // another port, so the client follows it with a new client.
  15154. static Result GetThroughTlsRedirectToDifferentPort(
  15155. const std::function<void(SSLClient &)> &setup,
  15156. const char *target_cert = SERVER_CERT2_FILE,
  15157. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15158. auto ssl_port = PORT + 1;
  15159. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15160. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15161. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15162. "/index");
  15163. });
  15164. SSLServer ssl_svr2(target_cert, target_key);
  15165. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15166. res.set_content("test", "text/plain");
  15167. });
  15168. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15169. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15170. auto se = detail::scope_exit([&] {
  15171. ssl_svr2.stop();
  15172. ssl_svr1.stop();
  15173. t2.join();
  15174. t.join();
  15175. });
  15176. ssl_svr1.wait_until_ready();
  15177. ssl_svr2.wait_until_ready();
  15178. SSLClient cli("127.0.0.1", PORT);
  15179. cli.set_follow_location(true);
  15180. cli.set_connection_timeout(30);
  15181. setup(cli);
  15182. return cli.Get("/index");
  15183. }
  15184. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15185. auto calls = 0;
  15186. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15187. cli.enable_server_certificate_verification(false);
  15188. // Accept the first server only.
  15189. cli.set_session_verifier([&](tls::session_t) {
  15190. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15191. : SSLVerifierResponse::CertificateRejected;
  15192. });
  15193. });
  15194. ASSERT_FALSE(res);
  15195. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15196. EXPECT_EQ(2, calls);
  15197. }
  15198. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15199. std::string pinned;
  15200. auto res = GetThroughTlsRedirectToDifferentPort(
  15201. [&](SSLClient &cli) {
  15202. cli.enable_server_certificate_verification(false);
  15203. // Pin the first certificate seen.
  15204. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15205. if (pinned.empty()) { pinned = ctx.serial(); }
  15206. return ctx.serial() == pinned;
  15207. });
  15208. },
  15209. // A certificate other than the first server's.
  15210. SERVER_CERT_FILE);
  15211. EXPECT_FALSE(res);
  15212. EXPECT_FALSE(pinned.empty());
  15213. }
  15214. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15215. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15216. std::string cert;
  15217. read_file(SERVER_CERT2_FILE, cert);
  15218. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15219. });
  15220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15221. EXPECT_EQ(StatusCode::OK_200, res->status);
  15222. }
  15223. // The target's certificate is signed by the root CA, which the first server's
  15224. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15225. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15226. auto res = GetThroughTlsRedirectToDifferentPort(
  15227. [](SSLClient &cli) {
  15228. std::string root_ca, cert;
  15229. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15230. read_file(SERVER_CERT2_FILE, cert);
  15231. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15232. cli.load_ca_cert_store(cert.data(), cert.size());
  15233. cli.enable_server_hostname_verification(false);
  15234. },
  15235. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. EXPECT_EQ(StatusCode::OK_200, res->status);
  15238. }
  15239. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15240. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15241. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15242. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15243. auto res = GetThroughTlsRedirectToDifferentPort(
  15244. [](SSLClient &cli) {
  15245. std::string root_ca, cert;
  15246. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15250. cli.enable_server_hostname_verification(false);
  15251. },
  15252. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15253. ASSERT_FALSE(res);
  15254. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15255. }
  15256. #endif
  15257. #endif
  15258. #ifdef CPPHTTPLIB_SSL_ENABLED
  15259. // Test that set_ca_cert_store() skips system certs (consistent with
  15260. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15261. // should be trusted - system certs should NOT be loaded.
  15262. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15263. // Load a specific cert that is NOT a system CA cert
  15264. std::string cert;
  15265. read_file(SERVER_CERT2_FILE, cert);
  15266. SSLClient cli("google.com");
  15267. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15268. cli.enable_server_certificate_verification(true);
  15269. // This should FAIL because:
  15270. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15271. // 2. System certs should NOT be loaded when custom store is set
  15272. // If system certs WERE loaded, this would succeed
  15273. auto res = cli.Get("/");
  15274. ASSERT_FALSE(res);
  15275. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15276. }
  15277. // Same as above, but through the native store handle path. Regression test:
  15278. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15279. // merged system certs into the user-provided store.
  15280. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15281. std::string cert;
  15282. read_file(SERVER_CERT2_FILE, cert);
  15283. SSLClient cli("google.com");
  15284. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15285. cli.enable_server_certificate_verification(true);
  15286. auto res = cli.Get("/");
  15287. ASSERT_FALSE(res);
  15288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15289. }
  15290. // A custom store set via the native handle must still verify a server whose
  15291. // cert it does contain.
  15292. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15293. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15294. ASSERT_TRUE(svr.is_valid());
  15295. svr.Get("/test", [&](const Request &, Response &res) {
  15296. res.set_content("test", "text/plain");
  15297. });
  15298. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15299. auto se = detail::scope_exit([&] {
  15300. svr.stop();
  15301. t.join();
  15302. ASSERT_FALSE(svr.is_running());
  15303. });
  15304. svr.wait_until_ready();
  15305. SSLClient cli("127.0.0.1", PORT);
  15306. std::string cert;
  15307. read_file(SERVER_CERT2_FILE, cert);
  15308. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15309. cli.enable_server_certificate_verification(true);
  15310. cli.set_connection_timeout(30);
  15311. auto res = cli.Get("/test");
  15312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15313. ASSERT_EQ(StatusCode::OK_200, res->status);
  15314. }
  15315. // CA certs loaded through the universal Client must be transferred to the
  15316. // client created internally for following an HTTPS redirect. Regression test:
  15317. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15318. // the CA data for redirect transfer.
  15319. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15320. auto ssl_port = PORT + 1;
  15321. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15322. ASSERT_TRUE(ssl_svr1.is_valid());
  15323. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15324. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15325. "/index");
  15326. });
  15327. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15328. ASSERT_TRUE(ssl_svr2.is_valid());
  15329. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15330. res.set_content("test", "text/plain");
  15331. });
  15332. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15333. thread t2 =
  15334. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15335. auto se = detail::scope_exit([&] {
  15336. ssl_svr2.stop();
  15337. ssl_svr1.stop();
  15338. t2.join();
  15339. t.join();
  15340. ASSERT_FALSE(ssl_svr1.is_running());
  15341. });
  15342. ssl_svr1.wait_until_ready();
  15343. ssl_svr2.wait_until_ready();
  15344. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15345. std::string cert;
  15346. read_file(SERVER_CERT2_FILE, cert);
  15347. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15348. cli.enable_server_certificate_verification(true);
  15349. cli.set_follow_location(true);
  15350. cli.set_connection_timeout(30);
  15351. auto res = cli.Get("/index");
  15352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15353. ASSERT_EQ(StatusCode::OK_200, res->status);
  15354. }
  15355. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15356. // so a host signed by a system CA verifies even though a custom CA is set
  15357. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15358. std::string cert;
  15359. read_file(SERVER_CERT2_FILE, cert);
  15360. SSLClient cli("google.com");
  15361. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15362. cli.enable_system_ca(true);
  15363. cli.enable_server_certificate_verification(true);
  15364. auto res = cli.Get("/");
  15365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15366. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15367. }
  15368. // The custom CA remains effective when combined with the system CA
  15369. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15370. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15371. ASSERT_TRUE(svr.is_valid());
  15372. svr.Get("/test", [&](const Request &, Response &res) {
  15373. res.set_content("test", "text/plain");
  15374. });
  15375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15376. auto se = detail::scope_exit([&] {
  15377. svr.stop();
  15378. t.join();
  15379. ASSERT_FALSE(svr.is_running());
  15380. });
  15381. svr.wait_until_ready();
  15382. SSLClient cli("127.0.0.1", PORT);
  15383. std::string cert;
  15384. read_file(SERVER_CERT2_FILE, cert);
  15385. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15386. cli.enable_system_ca(true);
  15387. cli.enable_server_certificate_verification(true);
  15388. cli.set_connection_timeout(30);
  15389. auto res = cli.Get("/test");
  15390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15391. ASSERT_EQ(StatusCode::OK_200, res->status);
  15392. }
  15393. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15394. // skip chain verification entirely (only the certificate identity was
  15395. // checked), so a server presenting an untrusted certificate with a matching
  15396. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15397. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15398. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15399. ASSERT_TRUE(svr.is_valid());
  15400. svr.Get("/test", [&](const Request &, Response &res) {
  15401. res.set_content("test", "text/plain");
  15402. });
  15403. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15404. auto se = detail::scope_exit([&] {
  15405. svr.stop();
  15406. t.join();
  15407. ASSERT_FALSE(svr.is_running());
  15408. });
  15409. svr.wait_until_ready();
  15410. SSLClient cli("127.0.0.1", PORT);
  15411. std::string cert;
  15412. // A trusted CA that did not sign the server certificate. The server cert
  15413. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15414. // this connection.
  15415. read_file(CLIENT_CA_CERT_FILE, cert);
  15416. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15417. cli.enable_server_certificate_verification(true);
  15418. cli.set_connection_timeout(30);
  15419. auto res = cli.Get("/test");
  15420. ASSERT_FALSE(res);
  15421. }
  15422. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15423. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15424. // CA that failed to come through fails verification instead of trusting them.
  15425. // (wolfSSL does not list the system CAs it loaded.)
  15426. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15427. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15428. ASSERT_TRUE(svr.is_valid());
  15429. auto port = svr.bind_to_any_port("127.0.0.1");
  15430. ASSERT_LT(0, port);
  15431. thread t = thread([&] { svr.listen_after_bind(); });
  15432. auto se = detail::scope_exit([&] {
  15433. svr.stop();
  15434. t.join();
  15435. ASSERT_FALSE(svr.is_running());
  15436. });
  15437. svr.wait_until_ready();
  15438. // The CAs a client trusts once its first request has loaded them
  15439. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15440. Client cli("https://127.0.0.1:" + std::to_string(port));
  15441. setup(cli);
  15442. cli.Get("/");
  15443. return tls::get_ca_names(cli.tls_context()).size();
  15444. };
  15445. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15446. EXPECT_EQ(0u,
  15447. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15448. }
  15449. #endif
  15450. // A TLS setting changed between requests applies to the next one, not just to
  15451. // the next connection
  15452. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15453. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15454. ASSERT_TRUE(svr.is_valid());
  15455. svr.Get("/", [](const Request &req, Response &res) {
  15456. res.set_content(std::to_string(req.remote_port), "text/plain");
  15457. });
  15458. auto port = svr.bind_to_any_port("127.0.0.1");
  15459. ASSERT_LT(0, port);
  15460. thread t = thread([&] { svr.listen_after_bind(); });
  15461. auto se = detail::scope_exit([&] {
  15462. svr.stop();
  15463. t.join();
  15464. ASSERT_FALSE(svr.is_running());
  15465. });
  15466. svr.wait_until_ready();
  15467. SSLClient cli("127.0.0.1", port);
  15468. cli.set_keep_alive(true);
  15469. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15470. cli.enable_server_certificate_verification(false);
  15471. // The port the request went out from, so a new one means a new connection
  15472. auto client_port = [&] {
  15473. auto res = cli.Get("/");
  15474. return res ? res->body : std::string();
  15475. };
  15476. auto last = client_port();
  15477. ASSERT_FALSE(last.empty());
  15478. // Setting a value it already has keeps the connection
  15479. cli.enable_server_certificate_verification(false);
  15480. cli.enable_server_hostname_verification(true);
  15481. EXPECT_EQ(last, client_port());
  15482. cli.enable_server_certificate_verification(true);
  15483. auto res = cli.Get("/");
  15484. EXPECT_FALSE(res);
  15485. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15486. std::string ca;
  15487. read_file(SERVER_CERT2_FILE, ca);
  15488. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15489. last = client_port();
  15490. ASSERT_FALSE(last.empty());
  15491. std::vector<std::function<void()>> setters = {
  15492. [&] { cli.enable_server_hostname_verification(false); },
  15493. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15494. [&] {
  15495. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15496. },
  15497. [&] {
  15498. cli.set_server_certificate_verifier(
  15499. [](const tls::VerifyContext &) { return true; });
  15500. },
  15501. [&] {
  15502. cli.set_session_verifier(
  15503. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15504. },
  15505. };
  15506. for (const auto &setter : setters) {
  15507. setter();
  15508. auto next = client_port();
  15509. ASSERT_FALSE(next.empty());
  15510. EXPECT_NE(last, next);
  15511. last = next;
  15512. }
  15513. cli.set_session_verifier(
  15514. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15515. auto handle = cli.open_stream("GET", "/");
  15516. EXPECT_FALSE(handle.is_valid());
  15517. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15518. }
  15519. // A PEM given to create_ca_store() needs no NUL after it
  15520. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15521. std::string pem;
  15522. read_file(SERVER_CERT2_FILE, pem);
  15523. auto buf = pem + "X";
  15524. auto store = tls::create_ca_store(buf.data(), pem.size());
  15525. EXPECT_TRUE(store != nullptr);
  15526. SSLClient cli("localhost");
  15527. cli.set_ca_cert_store(store);
  15528. }
  15529. // enable_system_ca(false) prevents system CA loading entirely
  15530. TEST(SSLClientTest, DisableSystemCa_Online) {
  15531. SSLClient cli("google.com");
  15532. cli.enable_system_ca(false);
  15533. cli.enable_server_certificate_verification(true);
  15534. auto res = cli.Get("/");
  15535. ASSERT_FALSE(res);
  15536. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15537. // itself when the CA chain is empty
  15538. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15539. res.error() == Error::SSLConnection);
  15540. }
  15541. // The universal Client forwards enable_system_ca()
  15542. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15543. std::string cert;
  15544. read_file(SERVER_CERT2_FILE, cert);
  15545. Client cli("https://google.com");
  15546. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15547. cli.enable_system_ca(true);
  15548. cli.enable_server_certificate_verification(true);
  15549. auto res = cli.Get("/");
  15550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15551. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15552. }
  15553. // The system CA policy must carry over to the client created internally for
  15554. // following a cross-host HTTPS redirect
  15555. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15556. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15557. ASSERT_TRUE(svr.is_valid());
  15558. svr.Get("/index", [&](const Request &, Response &res) {
  15559. res.set_redirect("https://www.google.com/");
  15560. });
  15561. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15562. auto se = detail::scope_exit([&] {
  15563. svr.stop();
  15564. t.join();
  15565. ASSERT_FALSE(svr.is_running());
  15566. });
  15567. svr.wait_until_ready();
  15568. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15569. std::string cert;
  15570. read_file(SERVER_CERT2_FILE, cert);
  15571. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15572. cli.enable_system_ca(true);
  15573. cli.enable_server_certificate_verification(true);
  15574. cli.set_follow_location(true);
  15575. cli.set_connection_timeout(30);
  15576. // Receiving any response proves the redirect client completed the TLS
  15577. // handshake with a system-CA-signed host
  15578. auto res = cli.Get("/index");
  15579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15580. }
  15581. TEST(MultipartFormDataTest, LargeData) {
  15582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15583. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15584. const ContentReader &content_reader) {
  15585. if (req.is_multipart_form_data()) {
  15586. std::vector<FormData> items;
  15587. content_reader(
  15588. [&](const FormData &file) {
  15589. items.push_back(file);
  15590. return true;
  15591. },
  15592. [&](const char *data, size_t data_length) {
  15593. items.back().content.append(data, data_length);
  15594. return true;
  15595. });
  15596. EXPECT_TRUE(std::string(items[0].name) == "document");
  15597. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15598. EXPECT_TRUE(items[0].filename == "2MB_data");
  15599. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15600. EXPECT_TRUE(items[1].name == "hello");
  15601. EXPECT_TRUE(items[1].content == "world");
  15602. EXPECT_TRUE(items[1].filename == "");
  15603. EXPECT_TRUE(items[1].content_type == "");
  15604. } else {
  15605. std::string body;
  15606. content_reader([&](const char *data, size_t data_length) {
  15607. body.append(data, data_length);
  15608. return true;
  15609. });
  15610. }
  15611. });
  15612. auto port = svr.bind_to_any_port(HOST);
  15613. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15614. auto se = detail::scope_exit([&] {
  15615. svr.stop();
  15616. t.join();
  15617. ASSERT_FALSE(svr.is_running());
  15618. });
  15619. svr.wait_until_ready();
  15620. {
  15621. std::string data(1024 * 1024 * 2, '.');
  15622. std::stringstream buffer;
  15623. buffer << data;
  15624. SSLClient cli(HOST, port);
  15625. cli.enable_server_certificate_verification(false);
  15626. UploadFormDataItems items{
  15627. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15628. {"hello", "world", "", ""},
  15629. };
  15630. auto res = cli.Post("/post", items);
  15631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15632. ASSERT_EQ(StatusCode::OK_200, res->status);
  15633. }
  15634. }
  15635. TEST(MultipartFormDataTest, DataProviderItems) {
  15636. std::random_device seed_gen;
  15637. std::mt19937 random(seed_gen());
  15638. std::string rand1;
  15639. rand1.resize(1000);
  15640. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15641. std::string rand2;
  15642. rand2.resize(3000);
  15643. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15645. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15646. const ContentReader &content_reader) {
  15647. ASSERT_FALSE(req.is_multipart_form_data());
  15648. std::string body;
  15649. content_reader([&](const char *data, size_t data_length) {
  15650. body.append(data, data_length);
  15651. return true;
  15652. });
  15653. EXPECT_EQ(body, "");
  15654. });
  15655. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15656. const ContentReader &content_reader) {
  15657. ASSERT_TRUE(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. ASSERT_TRUE(items.size() == 2);
  15669. EXPECT_EQ(std::string(items[0].name), "name1");
  15670. EXPECT_EQ(items[0].content, "Testing123");
  15671. EXPECT_EQ(items[0].filename, "filename1");
  15672. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15673. EXPECT_EQ(items[1].name, "name2");
  15674. EXPECT_EQ(items[1].content, "Testing456");
  15675. EXPECT_EQ(items[1].filename, "");
  15676. EXPECT_EQ(items[1].content_type, "");
  15677. });
  15678. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15679. const ContentReader &content_reader) {
  15680. ASSERT_TRUE(req.is_multipart_form_data());
  15681. std::vector<FormData> items;
  15682. content_reader(
  15683. [&](const FormData &file) {
  15684. items.push_back(file);
  15685. return true;
  15686. },
  15687. [&](const char *data, size_t data_length) {
  15688. items.back().content.append(data, data_length);
  15689. return true;
  15690. });
  15691. ASSERT_TRUE(items.size() == 2);
  15692. EXPECT_EQ(items[0].name, "name3");
  15693. EXPECT_EQ(items[0].content, rand1);
  15694. EXPECT_EQ(items[0].filename, "filename3");
  15695. EXPECT_EQ(items[0].content_type, "");
  15696. EXPECT_EQ(items[1].name, "name4");
  15697. EXPECT_EQ(items[1].content, rand2);
  15698. EXPECT_EQ(items[1].filename, "filename4");
  15699. EXPECT_EQ(items[1].content_type, "");
  15700. });
  15701. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15702. const ContentReader &content_reader) {
  15703. ASSERT_TRUE(req.is_multipart_form_data());
  15704. std::vector<FormData> items;
  15705. content_reader(
  15706. [&](const FormData &file) {
  15707. items.push_back(file);
  15708. return true;
  15709. },
  15710. [&](const char *data, size_t data_length) {
  15711. items.back().content.append(data, data_length);
  15712. return true;
  15713. });
  15714. ASSERT_TRUE(items.size() == 4);
  15715. EXPECT_EQ(std::string(items[0].name), "name1");
  15716. EXPECT_EQ(items[0].content, "Testing123");
  15717. EXPECT_EQ(items[0].filename, "filename1");
  15718. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15719. EXPECT_EQ(items[1].name, "name2");
  15720. EXPECT_EQ(items[1].content, "Testing456");
  15721. EXPECT_EQ(items[1].filename, "");
  15722. EXPECT_EQ(items[1].content_type, "");
  15723. EXPECT_EQ(items[2].name, "name3");
  15724. EXPECT_EQ(items[2].content, rand1);
  15725. EXPECT_EQ(items[2].filename, "filename3");
  15726. EXPECT_EQ(items[2].content_type, "");
  15727. EXPECT_EQ(items[3].name, "name4");
  15728. EXPECT_EQ(items[3].content, rand2);
  15729. EXPECT_EQ(items[3].filename, "filename4");
  15730. EXPECT_EQ(items[3].content_type, "");
  15731. });
  15732. auto port = svr.bind_to_any_port("localhost");
  15733. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15734. auto se = detail::scope_exit([&] {
  15735. svr.stop();
  15736. t.join();
  15737. ASSERT_FALSE(svr.is_running());
  15738. });
  15739. svr.wait_until_ready();
  15740. {
  15741. SSLClient cli("localhost", port);
  15742. cli.enable_server_certificate_verification(false);
  15743. UploadFormDataItems items{
  15744. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15745. {"name2", "Testing456", "", ""}, // not a file
  15746. };
  15747. {
  15748. auto res = cli.Post("/post-none", {}, {}, {});
  15749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15750. ASSERT_EQ(StatusCode::OK_200, res->status);
  15751. }
  15752. FormDataProviderItems providers;
  15753. {
  15754. auto res =
  15755. cli.Post("/post-items", {}, items, providers); // empty providers
  15756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15757. ASSERT_EQ(StatusCode::OK_200, res->status);
  15758. }
  15759. providers.push_back({"name3",
  15760. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15761. // test the offset is given correctly at each step
  15762. if (!offset)
  15763. sink.os.write(rand1.data(), 30);
  15764. else if (offset == 30)
  15765. sink.os.write(rand1.data() + 30, 300);
  15766. else if (offset == 330)
  15767. sink.os.write(rand1.data() + 330, 670);
  15768. else if (offset == rand1.size())
  15769. sink.done();
  15770. return true;
  15771. },
  15772. "filename3",
  15773. {}});
  15774. providers.push_back({"name4",
  15775. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15776. // test the offset is given correctly at each step
  15777. if (!offset)
  15778. sink.os.write(rand2.data(), 2000);
  15779. else if (offset == 2000)
  15780. sink.os.write(rand2.data() + 2000, 1);
  15781. else if (offset == 2001)
  15782. sink.os.write(rand2.data() + 2001, 999);
  15783. else if (offset == rand2.size())
  15784. sink.done();
  15785. return true;
  15786. },
  15787. "filename4",
  15788. {}});
  15789. {
  15790. auto res = cli.Post("/post-providers", {}, {}, providers);
  15791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15792. ASSERT_EQ(StatusCode::OK_200, res->status);
  15793. }
  15794. {
  15795. auto res = cli.Post("/post-both", {}, items, providers);
  15796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15797. ASSERT_EQ(StatusCode::OK_200, res->status);
  15798. }
  15799. }
  15800. }
  15801. TEST(MultipartFormDataTest, BadHeader) {
  15802. Server svr;
  15803. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15804. res.set_content("ok", "text/plain");
  15805. });
  15806. thread t = thread([&] { svr.listen(HOST, PORT); });
  15807. auto se = detail::scope_exit([&] {
  15808. svr.stop();
  15809. t.join();
  15810. ASSERT_FALSE(svr.is_running());
  15811. });
  15812. svr.wait_until_ready();
  15813. const std::string body =
  15814. "This is the preamble. It is to be ignored, though it\r\n"
  15815. "is a handy place for composition agents to include an\r\n"
  15816. "explanatory note to non-MIME conformant readers.\r\n"
  15817. "\r\n"
  15818. "\r\n"
  15819. "--simple boundary\r\n"
  15820. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15821. ": BAD...\r\n"
  15822. "\r\n"
  15823. "value1\r\n"
  15824. "--simple boundary\r\n"
  15825. "Content-Disposition: form-data; name=\"field2\"; "
  15826. "filename=\"example.txt\"\r\n"
  15827. "\r\n"
  15828. "value2\r\n"
  15829. "--simple boundary--\r\n"
  15830. "This is the epilogue. It is also to be ignored.\r\n";
  15831. std::string content_type =
  15832. R"(multipart/form-data; boundary="simple boundary")";
  15833. Client cli(HOST, PORT);
  15834. auto res = cli.Post("/post", body, content_type.c_str());
  15835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15836. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15837. }
  15838. TEST(MultipartFormDataTest, WithPreamble) {
  15839. Server svr;
  15840. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15841. res.set_content("ok", "text/plain");
  15842. });
  15843. thread t = thread([&] { svr.listen(HOST, PORT); });
  15844. auto se = detail::scope_exit([&] {
  15845. svr.stop();
  15846. t.join();
  15847. ASSERT_FALSE(svr.is_running());
  15848. });
  15849. svr.wait_until_ready();
  15850. const std::string body =
  15851. "This is the preamble. It is to be ignored, though it\r\n"
  15852. "is a handy place for composition agents to include an\r\n"
  15853. "explanatory note to non-MIME conformant readers.\r\n"
  15854. "\r\n"
  15855. "\r\n"
  15856. "--simple boundary\r\n"
  15857. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15858. "\r\n"
  15859. "value1\r\n"
  15860. "--simple boundary\r\n"
  15861. "Content-Disposition: form-data; name=\"field2\"; "
  15862. "filename=\"example.txt\"\r\n"
  15863. "\r\n"
  15864. "value2\r\n"
  15865. "--simple boundary--\r\n"
  15866. "This is the epilogue. It is also to be ignored.\r\n";
  15867. std::string content_type =
  15868. R"(multipart/form-data; boundary="simple boundary")";
  15869. Client cli(HOST, PORT);
  15870. auto res = cli.Post("/post", body, content_type.c_str());
  15871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15872. EXPECT_EQ(StatusCode::OK_200, res->status);
  15873. }
  15874. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15876. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15877. const ContentReader &content_reader) {
  15878. if (req.is_multipart_form_data()) {
  15879. std::vector<FormData> items;
  15880. content_reader(
  15881. [&](const FormData &file) {
  15882. items.push_back(file);
  15883. return true;
  15884. },
  15885. [&](const char *data, size_t data_length) {
  15886. items.back().content.append(data, data_length);
  15887. return true;
  15888. });
  15889. EXPECT_TRUE(std::string(items[0].name) == "document");
  15890. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15891. EXPECT_TRUE(items[0].filename == "2MB_data");
  15892. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15893. EXPECT_TRUE(items[1].name == "hello");
  15894. EXPECT_TRUE(items[1].content == "world");
  15895. EXPECT_TRUE(items[1].filename == "");
  15896. EXPECT_TRUE(items[1].content_type == "");
  15897. } else {
  15898. std::string body;
  15899. content_reader([&](const char *data, size_t data_length) {
  15900. body.append(data, data_length);
  15901. return true;
  15902. });
  15903. }
  15904. });
  15905. auto port = svr.bind_to_any_port("localhost");
  15906. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15907. auto se = detail::scope_exit([&] {
  15908. svr.stop();
  15909. t.join();
  15910. ASSERT_FALSE(svr.is_running());
  15911. });
  15912. svr.wait_until_ready();
  15913. {
  15914. std::string data(1024 * 1024 * 2, '.');
  15915. std::stringstream buffer;
  15916. buffer << data;
  15917. SSLClient cli("localhost", port);
  15918. cli.enable_server_certificate_verification(false);
  15919. UploadFormDataItems items{
  15920. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15921. {"hello", "world", "", ""},
  15922. };
  15923. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15925. ASSERT_EQ(StatusCode::OK_200, res->status);
  15926. }
  15927. }
  15928. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15929. std::string data(1024 * 1024 * 2, '&');
  15930. std::stringstream buffer;
  15931. buffer << data;
  15932. Client cli("https://localhost:8080");
  15933. UploadFormDataItems items{
  15934. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15935. {"hello", "world", "", ""},
  15936. };
  15937. for (const char &c : " \t\r\n") {
  15938. auto res =
  15939. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15940. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15941. ASSERT_FALSE(res);
  15942. }
  15943. }
  15944. TEST(MultipartFormDataTest, PutFormData) {
  15945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15946. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15947. const ContentReader &content_reader) {
  15948. if (req.is_multipart_form_data()) {
  15949. std::vector<FormData> items;
  15950. content_reader(
  15951. [&](const FormData &file) {
  15952. items.push_back(file);
  15953. return true;
  15954. },
  15955. [&](const char *data, size_t data_length) {
  15956. items.back().content.append(data, data_length);
  15957. return true;
  15958. });
  15959. EXPECT_TRUE(std::string(items[0].name) == "document");
  15960. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15961. EXPECT_TRUE(items[0].filename == "2MB_data");
  15962. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15963. EXPECT_TRUE(items[1].name == "hello");
  15964. EXPECT_TRUE(items[1].content == "world");
  15965. EXPECT_TRUE(items[1].filename == "");
  15966. EXPECT_TRUE(items[1].content_type == "");
  15967. } else {
  15968. std::string body;
  15969. content_reader([&](const char *data, size_t data_length) {
  15970. body.append(data, data_length);
  15971. return true;
  15972. });
  15973. }
  15974. });
  15975. auto port = svr.bind_to_any_port("localhost");
  15976. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15977. auto se = detail::scope_exit([&] {
  15978. svr.stop();
  15979. t.join();
  15980. ASSERT_FALSE(svr.is_running());
  15981. });
  15982. svr.wait_until_ready();
  15983. {
  15984. std::string data(1024 * 1024 * 2, '&');
  15985. std::stringstream buffer;
  15986. buffer << data;
  15987. SSLClient cli("localhost", port);
  15988. cli.enable_server_certificate_verification(false);
  15989. UploadFormDataItems items{
  15990. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15991. {"hello", "world", "", ""},
  15992. };
  15993. auto res = cli.Put("/put", items);
  15994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15995. ASSERT_EQ(StatusCode::OK_200, res->status);
  15996. }
  15997. }
  15998. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16000. svr.Put("/put_customboundary",
  16001. [&](const Request &req, const Response & /*res*/,
  16002. const ContentReader &content_reader) {
  16003. if (req.is_multipart_form_data()) {
  16004. std::vector<FormData> items;
  16005. content_reader(
  16006. [&](const FormData &file) {
  16007. items.push_back(file);
  16008. return true;
  16009. },
  16010. [&](const char *data, size_t data_length) {
  16011. items.back().content.append(data, data_length);
  16012. return true;
  16013. });
  16014. EXPECT_TRUE(std::string(items[0].name) == "document");
  16015. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16016. EXPECT_TRUE(items[0].filename == "2MB_data");
  16017. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16018. EXPECT_TRUE(items[1].name == "hello");
  16019. EXPECT_TRUE(items[1].content == "world");
  16020. EXPECT_TRUE(items[1].filename == "");
  16021. EXPECT_TRUE(items[1].content_type == "");
  16022. } else {
  16023. std::string body;
  16024. content_reader([&](const char *data, size_t data_length) {
  16025. body.append(data, data_length);
  16026. return true;
  16027. });
  16028. }
  16029. });
  16030. auto port = svr.bind_to_any_port("localhost");
  16031. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16032. auto se = detail::scope_exit([&] {
  16033. svr.stop();
  16034. t.join();
  16035. ASSERT_FALSE(svr.is_running());
  16036. });
  16037. svr.wait_until_ready();
  16038. {
  16039. std::string data(1024 * 1024 * 2, '&');
  16040. std::stringstream buffer;
  16041. buffer << data;
  16042. SSLClient cli("localhost", port);
  16043. cli.enable_server_certificate_verification(false);
  16044. UploadFormDataItems items{
  16045. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16046. {"hello", "world", "", ""},
  16047. };
  16048. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16050. ASSERT_EQ(StatusCode::OK_200, res->status);
  16051. }
  16052. }
  16053. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16054. std::string data(1024 * 1024 * 2, '&');
  16055. std::stringstream buffer;
  16056. buffer << data;
  16057. Client cli("https://localhost:8080");
  16058. cli.enable_server_certificate_verification(false);
  16059. UploadFormDataItems items{
  16060. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16061. {"hello", "world", "", ""},
  16062. };
  16063. for (const char &c : " \t\r\n") {
  16064. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16065. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16066. ASSERT_FALSE(res);
  16067. }
  16068. }
  16069. TEST(MultipartFormDataTest, AlternateFilename) {
  16070. auto handled = false;
  16071. Server svr;
  16072. svr.Post("/test", [&](const Request &req, Response &res) {
  16073. ASSERT_EQ(2u, req.form.files.size());
  16074. ASSERT_EQ(1u, req.form.fields.size());
  16075. // Test files
  16076. const auto &file1 = req.form.get_file("file1");
  16077. ASSERT_EQ("file1", file1.name);
  16078. ASSERT_EQ("A.txt", file1.filename);
  16079. ASSERT_EQ("text/plain", file1.content_type);
  16080. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16081. const auto &file2 = req.form.get_file("file2");
  16082. ASSERT_EQ("file2", file2.name);
  16083. ASSERT_EQ("a.html", file2.filename);
  16084. ASSERT_EQ("text/html", file2.content_type);
  16085. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16086. file2.content);
  16087. // Test text field
  16088. const auto &text = req.form.get_field("text");
  16089. ASSERT_EQ("text default", text);
  16090. res.set_content("ok", "text/plain");
  16091. handled = true;
  16092. });
  16093. thread t = thread([&] { svr.listen(HOST, PORT); });
  16094. auto se = detail::scope_exit([&] {
  16095. svr.stop();
  16096. t.join();
  16097. ASSERT_FALSE(svr.is_running());
  16098. ASSERT_TRUE(handled);
  16099. });
  16100. svr.wait_until_ready();
  16101. auto req = "POST /test HTTP/1.1\r\n"
  16102. "Host: localhost\r\n"
  16103. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16104. "Content-Length: 399\r\n"
  16105. "\r\n"
  16106. "----------\r\n"
  16107. "Content-Disposition: form-data; name=\"text\"\r\n"
  16108. "\r\n"
  16109. "text default\r\n"
  16110. "----------\r\n"
  16111. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16112. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16113. "Content-Type: text/plain\r\n"
  16114. "\r\n"
  16115. "Content of a.txt.\r\n"
  16116. "\r\n"
  16117. "----------\r\n"
  16118. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16119. "\"a.html\"\r\n"
  16120. "Content-Type: text/html\r\n"
  16121. "\r\n"
  16122. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16123. "\r\n"
  16124. "------------\r\n";
  16125. ASSERT_TRUE(send_request(1, req));
  16126. }
  16127. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16128. auto handled = false;
  16129. Server svr;
  16130. svr.Post("/test", [&](const Request &req, Response &res) {
  16131. // Case-insensitive "utf-8''" prefix with a long value
  16132. const auto &file = req.form.get_file("file1");
  16133. ASSERT_EQ("file1", file.name);
  16134. // 8000 chars exercises both the Content-Disposition parser and the
  16135. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16136. // Prior to the fix, std::regex_match on this header would cause O(N)
  16137. // stack recursion in libstdc++, leading to SIGSEGV.
  16138. std::string expected_filename(8000, 'A');
  16139. ASSERT_EQ(expected_filename, file.filename);
  16140. res.set_content("ok", "text/plain");
  16141. handled = true;
  16142. });
  16143. thread t = thread([&] { svr.listen(HOST, PORT); });
  16144. auto se = detail::scope_exit([&] {
  16145. svr.stop();
  16146. t.join();
  16147. ASSERT_FALSE(svr.is_running());
  16148. ASSERT_TRUE(handled);
  16149. });
  16150. svr.wait_until_ready();
  16151. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16152. // Regression test for GHSA-qq6v-r583-3h69
  16153. std::string long_filename(8000, 'A');
  16154. std::string body = "----------\r\n"
  16155. "Content-Disposition: form-data; name=\"file1\"; "
  16156. "filename*=\"Utf-8''" +
  16157. long_filename +
  16158. "\"\r\n"
  16159. "\r\n"
  16160. "hello\r\n"
  16161. "------------\r\n";
  16162. auto req = "POST /test HTTP/1.1\r\n"
  16163. "Host: localhost\r\n"
  16164. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16165. "Content-Length: " +
  16166. std::to_string(body.size()) + "\r\n\r\n" + body;
  16167. ASSERT_TRUE(send_request(1, req));
  16168. }
  16169. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16170. auto handled = false;
  16171. Server svr;
  16172. svr.Post("/test", [&](const Request &req, Response &) {
  16173. ASSERT_EQ(2u, req.form.fields.size());
  16174. const auto &text1 = req.form.get_field("text1");
  16175. ASSERT_EQ("text1", text1);
  16176. const auto &text2 = req.form.get_field("text2");
  16177. ASSERT_EQ("text2", text2);
  16178. handled = true;
  16179. });
  16180. thread t = thread([&] { svr.listen(HOST, PORT); });
  16181. auto se = detail::scope_exit([&] {
  16182. svr.stop();
  16183. t.join();
  16184. ASSERT_FALSE(svr.is_running());
  16185. ASSERT_TRUE(handled);
  16186. });
  16187. svr.wait_until_ready();
  16188. auto req = "POST /test HTTP/1.1\r\n"
  16189. "Host: localhost\r\n"
  16190. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16191. "Content-Length: 146\r\n"
  16192. "\r\n----------\r\n"
  16193. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16194. "\r\n"
  16195. "text1"
  16196. "\r\n----------\r\n"
  16197. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16198. "\r\n"
  16199. "text2"
  16200. "\r\n------------";
  16201. std::string response;
  16202. ASSERT_TRUE(send_request(1, req, &response));
  16203. ASSERT_EQ("200", response.substr(9, 3));
  16204. }
  16205. TEST(MultipartFormDataTest, ContentLength) {
  16206. auto handled = false;
  16207. Server svr;
  16208. svr.Post("/test", [&](const Request &req, Response &) {
  16209. ASSERT_EQ(2u, req.form.fields.size());
  16210. const auto &text1 = req.form.get_field("text1");
  16211. ASSERT_EQ("text1", text1);
  16212. const auto &text2 = req.form.get_field("text2");
  16213. ASSERT_EQ("text2", text2);
  16214. handled = true;
  16215. });
  16216. thread t = thread([&] { svr.listen(HOST, PORT); });
  16217. auto se = detail::scope_exit([&] {
  16218. svr.stop();
  16219. t.join();
  16220. ASSERT_FALSE(svr.is_running());
  16221. ASSERT_TRUE(handled);
  16222. });
  16223. svr.wait_until_ready();
  16224. auto req = "POST /test HTTP/1.1\r\n"
  16225. "Host: localhost\r\n"
  16226. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16227. "Content-Length: 167\r\n"
  16228. "\r\n----------\r\n"
  16229. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16230. "Content-Length: 5\r\n"
  16231. "\r\n"
  16232. "text1"
  16233. "\r\n----------\r\n"
  16234. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16235. "\r\n"
  16236. "text2"
  16237. "\r\n------------\r\n";
  16238. std::string response;
  16239. ASSERT_TRUE(send_request(1, req, &response));
  16240. ASSERT_EQ("200", response.substr(9, 3));
  16241. }
  16242. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16243. auto handled = false;
  16244. Server svr;
  16245. svr.Post("/test", [&](const Request &req, Response &) {
  16246. ASSERT_EQ(2u, req.form.fields.size());
  16247. const auto &text1 = req.form.get_field("text1");
  16248. ASSERT_EQ("text1", text1);
  16249. // TODO: Add header access for text fields if needed
  16250. const auto &text2 = req.form.get_field("text2");
  16251. ASSERT_EQ("text2", text2);
  16252. // TODO: Header access for text fields needs to be implemented
  16253. // auto &headers = it->second.headers;
  16254. // ASSERT_EQ(3U, headers.size());
  16255. // auto custom_header = headers.find("x-whatever");
  16256. // ASSERT_TRUE(custom_header != headers.end());
  16257. // ASSERT_NE("customvalue", custom_header->second);
  16258. // ASSERT_EQ("CustomValue", custom_header->second);
  16259. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16260. handled = true;
  16261. });
  16262. thread t = thread([&] { svr.listen(HOST, PORT); });
  16263. auto se = detail::scope_exit([&] {
  16264. svr.stop();
  16265. t.join();
  16266. ASSERT_FALSE(svr.is_running());
  16267. ASSERT_TRUE(handled);
  16268. });
  16269. svr.wait_until_ready();
  16270. auto req = "POST /test HTTP/1.1\r\n"
  16271. "Host: localhost\r\n"
  16272. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16273. "Content-Length: 232\r\n"
  16274. "\r\n----------\r\n"
  16275. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16276. "Content-Length: 5\r\n"
  16277. "X-Test: 1\r\n"
  16278. "\r\n"
  16279. "text1"
  16280. "\r\n----------\r\n"
  16281. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16282. "Content-Type: text/plain\r\n"
  16283. "X-Whatever: CustomValue\r\n"
  16284. "\r\n"
  16285. "text2"
  16286. "\r\n------------\r\n"
  16287. "That should be disregarded. Not even read";
  16288. std::string response;
  16289. ASSERT_TRUE(send_request(1, req, &response));
  16290. ASSERT_EQ("200", response.substr(9, 3));
  16291. }
  16292. TEST(MultipartFormDataTest, LargeHeader) {
  16293. auto handled = false;
  16294. Server svr;
  16295. svr.Post("/test", [&](const Request &req, Response &) {
  16296. ASSERT_EQ(1u, req.form.fields.size());
  16297. const auto &text = req.form.get_field("name1");
  16298. ASSERT_EQ("text1", text);
  16299. handled = true;
  16300. });
  16301. thread t = thread([&] { svr.listen(HOST, PORT); });
  16302. auto se = detail::scope_exit([&] {
  16303. svr.stop();
  16304. t.join();
  16305. ASSERT_FALSE(svr.is_running());
  16306. ASSERT_TRUE(handled);
  16307. });
  16308. svr.wait_until_ready();
  16309. auto boundary = std::string("cpp-httplib-multipart-data");
  16310. std::string content = "--" + boundary +
  16311. "\r\n"
  16312. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16313. "\r\n"
  16314. "text1\r\n"
  16315. "--" +
  16316. boundary + "--\r\n";
  16317. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16318. "Host: localhost\r\n"
  16319. "Content-Type: multipart/form-data;boundary=" +
  16320. boundary +
  16321. "\r\n"
  16322. "Content-Length: " +
  16323. std::to_string(content.size()) +
  16324. "\r\n"
  16325. "Dummy-Header: ";
  16326. std::string header_suffix = "\r\n"
  16327. "\r\n";
  16328. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16329. size_t header_dummy_size =
  16330. read_buff_size -
  16331. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16332. auto header_dummy = std::string(header_dummy_size, '@');
  16333. auto req = header_prefix + header_dummy + header_suffix + content;
  16334. std::string response;
  16335. ASSERT_TRUE(send_request(1, req, &response));
  16336. ASSERT_EQ("200", response.substr(9, 3));
  16337. }
  16338. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16339. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16340. // (not chunked Transfer-Encoding) after the streaming refactor.
  16341. auto handled = false;
  16342. Server svr;
  16343. svr.Post("/upload", [&](const Request &req, Response &res) {
  16344. auto cl_it = req.headers.find("Content-Length");
  16345. EXPECT_TRUE(cl_it != req.headers.end());
  16346. auto te_it = req.headers.find("Transfer-Encoding");
  16347. EXPECT_TRUE(te_it == req.headers.end());
  16348. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16349. res.set_content("ok", "text/plain");
  16350. handled = true;
  16351. });
  16352. auto port = svr.bind_to_any_port(HOST);
  16353. auto t = thread([&] { svr.listen_after_bind(); });
  16354. auto se = detail::scope_exit([&] {
  16355. svr.stop();
  16356. t.join();
  16357. ASSERT_FALSE(svr.is_running());
  16358. ASSERT_TRUE(handled);
  16359. });
  16360. svr.wait_until_ready();
  16361. UploadFormDataItems items = {
  16362. {"field1", "hello", "", "text/plain"},
  16363. {"file1", "world", "test.txt", "application/octet-stream"},
  16364. };
  16365. Client cli(HOST, port);
  16366. auto res = cli.Post("/upload", {}, items);
  16367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16368. EXPECT_EQ(StatusCode::OK_200, res->status);
  16369. }
  16370. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16371. // Verify that make_multipart_content_provider coalesces many small segments
  16372. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16373. constexpr size_t kItemCount = 1000;
  16374. UploadFormDataItems items;
  16375. items.reserve(kItemCount);
  16376. for (size_t i = 0; i < kItemCount; i++) {
  16377. items.push_back(
  16378. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16379. }
  16380. const std::string boundary = "----test-boundary";
  16381. auto content_length = detail::get_multipart_content_length(items, boundary);
  16382. auto provider = detail::make_multipart_content_provider(items, boundary);
  16383. // Drive the provider the same way write_content_with_progress does
  16384. size_t write_count = 0;
  16385. size_t total_bytes = 0;
  16386. DataSink sink;
  16387. size_t offset = 0;
  16388. sink.write = [&](const char *d, size_t l) -> bool {
  16389. (void)d;
  16390. write_count++;
  16391. total_bytes += l;
  16392. offset += l;
  16393. return true;
  16394. };
  16395. sink.is_writable = []() -> bool { return true; };
  16396. while (offset < content_length) {
  16397. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16398. }
  16399. EXPECT_EQ(content_length, total_bytes);
  16400. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16401. // With buffering into 64KB blocks, write_count should be much smaller.
  16402. auto segment_count = 3 * kItemCount + 1;
  16403. EXPECT_LT(write_count, segment_count / 10);
  16404. }
  16405. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16406. // Integration test: send many UploadFormDataItems and verify the server
  16407. // receives all of them correctly (#2410).
  16408. constexpr size_t kItemCount = 500;
  16409. auto handled = false;
  16410. Server svr;
  16411. svr.Post("/upload", [&](const Request &req, Response &res) {
  16412. EXPECT_EQ(kItemCount, req.form.fields.size());
  16413. for (size_t i = 0; i < kItemCount; i++) {
  16414. auto key = "field" + std::to_string(i);
  16415. auto val = "value" + std::to_string(i);
  16416. auto it = req.form.fields.find(key);
  16417. if (it != req.form.fields.end()) {
  16418. EXPECT_EQ(val, it->second.content);
  16419. } else {
  16420. ADD_FAILURE() << "Missing field: " << key;
  16421. }
  16422. }
  16423. res.set_content("ok", "text/plain");
  16424. handled = true;
  16425. });
  16426. auto port = svr.bind_to_any_port(HOST);
  16427. auto t = thread([&] { svr.listen_after_bind(); });
  16428. auto se = detail::scope_exit([&] {
  16429. svr.stop();
  16430. t.join();
  16431. ASSERT_FALSE(svr.is_running());
  16432. ASSERT_TRUE(handled);
  16433. });
  16434. svr.wait_until_ready();
  16435. UploadFormDataItems items;
  16436. items.reserve(kItemCount);
  16437. for (size_t i = 0; i < kItemCount; i++) {
  16438. items.push_back(
  16439. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16440. }
  16441. Client cli(HOST, port);
  16442. auto res = cli.Post("/upload", items);
  16443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16444. EXPECT_EQ(StatusCode::OK_200, res->status);
  16445. }
  16446. TEST(MultipartFormDataTest, MakeFileProvider) {
  16447. // Verify make_file_provider sends a file's contents correctly.
  16448. const std::string file_content(4096, 'Z');
  16449. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16450. {
  16451. std::ofstream ofs(tmp_path, std::ios::binary);
  16452. ofs.write(file_content.data(),
  16453. static_cast<std::streamsize>(file_content.size()));
  16454. }
  16455. auto handled = false;
  16456. Server svr;
  16457. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16458. const ContentReader &content_reader) {
  16459. ASSERT_TRUE(req.is_multipart_form_data());
  16460. std::vector<FormData> items;
  16461. content_reader(
  16462. [&](const FormData &file) {
  16463. items.push_back(file);
  16464. return true;
  16465. },
  16466. [&](const char *data, size_t data_length) {
  16467. items.back().content.append(data, data_length);
  16468. return true;
  16469. });
  16470. ASSERT_EQ(1u, items.size());
  16471. EXPECT_EQ("myfile", items[0].name);
  16472. EXPECT_EQ("data.bin", items[0].filename);
  16473. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16474. EXPECT_EQ(file_content, items[0].content);
  16475. handled = true;
  16476. });
  16477. auto port = svr.bind_to_any_port(HOST);
  16478. auto t = thread([&] { svr.listen_after_bind(); });
  16479. auto se = detail::scope_exit([&] {
  16480. svr.stop();
  16481. t.join();
  16482. ASSERT_FALSE(svr.is_running());
  16483. ASSERT_TRUE(handled);
  16484. std::remove(tmp_path.c_str());
  16485. });
  16486. svr.wait_until_ready();
  16487. FormDataProviderItems providers;
  16488. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16489. "application/octet-stream"));
  16490. Client cli(HOST, port);
  16491. auto res = cli.Post("/upload", {}, {}, providers);
  16492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16493. EXPECT_EQ(StatusCode::OK_200, res->status);
  16494. }
  16495. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16496. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16497. // (100) headers is rejected with a 400 Bad Request response.
  16498. Server svr;
  16499. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16500. res.set_content("ok", "text/plain");
  16501. });
  16502. thread t = thread([&] { svr.listen(HOST, PORT); });
  16503. auto se = detail::scope_exit([&] {
  16504. svr.stop();
  16505. t.join();
  16506. ASSERT_FALSE(svr.is_running());
  16507. });
  16508. svr.wait_until_ready();
  16509. // Build a multipart part with 101 custom headers (exceeding
  16510. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16511. std::stringstream body;
  16512. body << "--simpleboundary\r\n"
  16513. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16514. for (int i = 0; i < 101; i++) {
  16515. body << "X-Custom-Header-" << i << ": value\r\n";
  16516. }
  16517. body << "\r\n"
  16518. << "value1\r\n"
  16519. << "--simpleboundary--\r\n";
  16520. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16521. Client cli(HOST, PORT);
  16522. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16524. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16525. }
  16526. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16527. // A body that never contains the declared boundary must not be accumulated
  16528. // while the parser waits for it. Buffering it would also make every read
  16529. // rescan everything seen so far, which is quadratic in the body size.
  16530. Server svr;
  16531. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16532. res.set_content("ok", "text/plain");
  16533. });
  16534. auto port = svr.bind_to_any_port(HOST);
  16535. thread t = thread([&] { svr.listen_after_bind(); });
  16536. auto se = detail::scope_exit([&] {
  16537. svr.stop();
  16538. t.join();
  16539. ASSERT_FALSE(svr.is_running());
  16540. });
  16541. svr.wait_until_ready();
  16542. Client cli(HOST, port);
  16543. cli.set_read_timeout(60, 0);
  16544. cli.set_write_timeout(60, 0);
  16545. // '-' is the worst case: it matches the first character of the boundary, so
  16546. // every position has to be checked against it.
  16547. auto post_dashes = [&](size_t size) {
  16548. const std::string body(size, '-');
  16549. auto start = std::chrono::steady_clock::now();
  16550. auto res =
  16551. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16552. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16553. std::chrono::steady_clock::now() - start)
  16554. .count();
  16555. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16556. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16557. return ms;
  16558. };
  16559. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16560. // Windows.
  16561. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16562. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16563. // Comparing the two sizes rather than checking an absolute duration keeps
  16564. // this meaningful across build types and CI load, both of which move the
  16565. // absolute numbers by more than an order of magnitude. Four times the bytes
  16566. // costs about four times the time when parsing is linear, and about sixteen
  16567. // times when the body is buffered and rescanned.
  16568. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16569. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16570. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16571. << "ms, which suggests the body is being buffered and rescanned";
  16572. }
  16573. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16574. // A boundary can only be followed by CRLF or by "--", so anything else is
  16575. // malformed no matter what comes next. The parser must say so right away
  16576. // instead of buffering the rest of the declared body.
  16577. Server svr;
  16578. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16579. res.set_content("ok", "text/plain");
  16580. });
  16581. auto port = svr.bind_to_any_port(HOST);
  16582. thread t = thread([&] { svr.listen_after_bind(); });
  16583. auto se = detail::scope_exit([&] {
  16584. svr.stop();
  16585. t.join();
  16586. ASSERT_FALSE(svr.is_running());
  16587. });
  16588. svr.wait_until_ready();
  16589. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16590. // buffers instead of failing would still be waiting for the remaining bytes.
  16591. const std::string body = "--zzzz\r\n"
  16592. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16593. "\r\n"
  16594. "text1"
  16595. "\r\n--zzzzXX";
  16596. const std::string req = "POST /post HTTP/1.1\r\n"
  16597. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16598. "Content-Length: 1048576\r\n"
  16599. "\r\n" +
  16600. body;
  16601. std::string response;
  16602. ASSERT_TRUE(send_request(3, req, &response, port));
  16603. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16604. EXPECT_EQ("400", response.substr(9, 3));
  16605. }
  16606. // Posts a multipart body split into two writes, so that the server sees the
  16607. // split at whatever offset the caller chose, and expects the single "text1"
  16608. // field to come through.
  16609. static void expect_split_multipart_ok(const std::string &body1,
  16610. const std::string &body2) {
  16611. auto handled = false;
  16612. Server svr;
  16613. svr.Post("/post", [&](const Request &req, Response &) {
  16614. EXPECT_EQ(1u, req.form.fields.size());
  16615. EXPECT_EQ("text1", req.form.get_field("text1"));
  16616. handled = true;
  16617. });
  16618. auto port = svr.bind_to_any_port(HOST);
  16619. thread t = thread([&] { svr.listen_after_bind(); });
  16620. auto se = detail::scope_exit([&] {
  16621. svr.stop();
  16622. t.join();
  16623. ASSERT_FALSE(svr.is_running());
  16624. ASSERT_TRUE(handled);
  16625. });
  16626. svr.wait_until_ready();
  16627. // "Connection: close" makes the server close once it has answered, so the
  16628. // response drain ends immediately instead of idling until the read timeout.
  16629. const std::string head =
  16630. "POST /post HTTP/1.1\r\n"
  16631. "Host: localhost\r\n"
  16632. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16633. "Connection: close\r\n"
  16634. "Content-Length: " +
  16635. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16636. std::string response;
  16637. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16638. ASSERT_GE(response.size(), 12u) << "no response";
  16639. EXPECT_EQ("200", response.substr(9, 3));
  16640. }
  16641. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16642. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16643. // ignored, including when it does not arrive in the same read as the
  16644. // close-delimiter itself.
  16645. expect_split_multipart_ok("--zzzz\r\n"
  16646. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16647. "\r\n"
  16648. "text1"
  16649. "\r\n--zzzz--",
  16650. "\r\nthis epilogue must be ignored\r\n");
  16651. }
  16652. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16653. // The initial boundary may be preceded by a preamble of any length and may
  16654. // straddle a read boundary. Discarding data while waiting for it must not
  16655. // throw away a partial boundary sitting at the end of the buffer.
  16656. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16657. "zz\r\n"
  16658. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16659. "\r\n"
  16660. "text1"
  16661. "\r\n--zzzz--\r\n");
  16662. }
  16663. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16664. // The received boundary was only checked for being non-empty, so it could be
  16665. // as long as a header is allowed to be. The parser scans the body for
  16666. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16667. // costs a nearly full comparison at nearly every position, making the
  16668. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16669. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16670. Server svr;
  16671. svr.Post("/post", [](const Request &req, Response &res) {
  16672. EXPECT_EQ(1u, req.form.fields.size());
  16673. EXPECT_EQ("text1", req.form.get_field("text1"));
  16674. res.set_content("ok", "text/plain");
  16675. });
  16676. auto port = svr.bind_to_any_port(HOST);
  16677. thread t = thread([&] { svr.listen_after_bind(); });
  16678. auto se = detail::scope_exit([&] {
  16679. svr.stop();
  16680. t.join();
  16681. ASSERT_FALSE(svr.is_running());
  16682. });
  16683. svr.wait_until_ready();
  16684. Client cli(HOST, port);
  16685. auto post_with_boundary_of_length = [&](size_t len) {
  16686. const std::string boundary(len, 'a');
  16687. const std::string body =
  16688. "--" + boundary +
  16689. "\r\n"
  16690. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16691. "\r\n"
  16692. "text1"
  16693. "\r\n--" +
  16694. boundary + "--\r\n";
  16695. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16696. };
  16697. auto res = post_with_boundary_of_length(70);
  16698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16699. EXPECT_EQ(StatusCode::OK_200, res->status);
  16700. res = post_with_boundary_of_length(71);
  16701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16702. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16703. }
  16704. TEST(MakeFileBodyTest, Basic) {
  16705. const std::string file_content(4096, 'Z');
  16706. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16707. {
  16708. std::ofstream ofs(tmp_path, std::ios::binary);
  16709. ofs.write(file_content.data(),
  16710. static_cast<std::streamsize>(file_content.size()));
  16711. }
  16712. auto handled = false;
  16713. Server svr;
  16714. svr.Post("/upload", [&](const Request &req, Response &res) {
  16715. EXPECT_EQ(file_content, req.body);
  16716. handled = true;
  16717. res.status = StatusCode::OK_200;
  16718. });
  16719. auto port = svr.bind_to_any_port(HOST);
  16720. auto t = thread([&] { svr.listen_after_bind(); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. t.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. ASSERT_TRUE(handled);
  16726. std::remove(tmp_path.c_str());
  16727. });
  16728. svr.wait_until_ready();
  16729. auto fb = make_file_body(tmp_path);
  16730. ASSERT_GT(fb.first, 0u);
  16731. Client cli(HOST, port);
  16732. auto res =
  16733. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16735. EXPECT_EQ(StatusCode::OK_200, res->status);
  16736. }
  16737. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16738. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16739. {
  16740. std::ofstream ofs(path, std::ios::binary);
  16741. const std::string content(100, 'A');
  16742. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16743. }
  16744. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16745. auto body = make_file_body(path);
  16746. ASSERT_EQ(100u, body.first);
  16747. ASSERT_TRUE(static_cast<bool>(body.second));
  16748. // Rewritten shorter after its length was measured - and, on a server, after
  16749. // that length has already gone out as Content-Length.
  16750. {
  16751. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16752. const std::string content(10, 'A');
  16753. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16754. }
  16755. std::string written;
  16756. DataSink sink;
  16757. sink.write = [&](const char *d, size_t l) {
  16758. written.append(d, l);
  16759. return true;
  16760. };
  16761. // The provider has to report failure. write_content_with_progress() advances
  16762. // its offset only by what was written, so a provider that returns true
  16763. // without completing the length it promised is called again straight away,
  16764. // and again.
  16765. EXPECT_FALSE(body.second(0, body.first, sink));
  16766. EXPECT_EQ(std::string(10, 'A'), written);
  16767. }
  16768. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16769. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16770. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16771. {
  16772. std::ofstream ofs(path, std::ios::binary);
  16773. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16774. }
  16775. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16776. auto body = make_file_body(path);
  16777. ASSERT_EQ(content.size(), body.first);
  16778. ASSERT_TRUE(static_cast<bool>(body.second));
  16779. std::string written;
  16780. DataSink sink;
  16781. sink.write = [&](const char *d, size_t l) {
  16782. written.append(d, l);
  16783. return true;
  16784. };
  16785. EXPECT_TRUE(body.second(0, body.first, sink));
  16786. EXPECT_EQ(content, written);
  16787. }
  16788. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16789. static constexpr unsigned int number_of_tasks{1000000};
  16790. std::atomic_uint count{0};
  16791. std::unique_ptr<TaskQueue> task_queue{
  16792. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16793. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16794. auto queued = task_queue->enqueue(
  16795. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16796. EXPECT_TRUE(queued);
  16797. }
  16798. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16799. task_queue->shutdown();
  16800. #else
  16801. EXPECT_NO_THROW(task_queue->shutdown());
  16802. #endif
  16803. EXPECT_EQ(number_of_tasks, count.load());
  16804. }
  16805. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16806. static constexpr unsigned int number_of_tasks{1000000};
  16807. static constexpr unsigned int qlimit{2};
  16808. unsigned int queued_count{0};
  16809. std::atomic_uint count{0};
  16810. std::unique_ptr<TaskQueue> task_queue{
  16811. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16812. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16813. if (task_queue->enqueue(
  16814. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16815. queued_count++;
  16816. }
  16817. }
  16818. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16819. task_queue->shutdown();
  16820. #else
  16821. EXPECT_NO_THROW(task_queue->shutdown());
  16822. #endif
  16823. EXPECT_EQ(queued_count, count.load());
  16824. EXPECT_TRUE(queued_count <= number_of_tasks);
  16825. EXPECT_TRUE(queued_count >= qlimit);
  16826. }
  16827. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16828. // Use a short idle timeout so a dynamic thread spawns, times out and
  16829. // exits during the test, and the pool keeps working afterwards.
  16830. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16831. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16832. /*idle_timeout_sec=*/1}};
  16833. std::atomic_uint count{0};
  16834. std::condition_variable cv;
  16835. std::mutex mtx;
  16836. bool release = false;
  16837. // Block the base thread so the second task spawns a dynamic thread.
  16838. EXPECT_TRUE(task_queue->enqueue([&] {
  16839. std::unique_lock<std::mutex> lock(mtx);
  16840. while (!release) {
  16841. cv.wait(lock);
  16842. }
  16843. count++;
  16844. }));
  16845. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16846. // Let the dynamic thread finish its task and exceed the idle timeout.
  16847. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16848. {
  16849. std::unique_lock<std::mutex> lock(mtx);
  16850. release = true;
  16851. }
  16852. cv.notify_all();
  16853. // The pool must still accept and run tasks after the dynamic thread exited.
  16854. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16855. task_queue->shutdown();
  16856. EXPECT_EQ(3u, count.load());
  16857. }
  16858. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16859. static constexpr size_t number_of_tasks{32};
  16860. std::unique_ptr<TaskQueue> task_queue{
  16861. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16862. // Let the base threads go idle so the burst below finds them waiting.
  16863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16864. std::mutex mtx;
  16865. std::condition_variable cv;
  16866. size_t running = 0;
  16867. bool release = false;
  16868. for (size_t i = 0; i < number_of_tasks; i++) {
  16869. EXPECT_TRUE(task_queue->enqueue([&] {
  16870. std::unique_lock<std::mutex> lock(mtx);
  16871. running++;
  16872. cv.notify_all();
  16873. cv.wait(lock, [&] { return release; });
  16874. }));
  16875. }
  16876. {
  16877. std::unique_lock<std::mutex> lock(mtx);
  16878. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16879. [&] { return running == number_of_tasks; }));
  16880. release = true;
  16881. }
  16882. cv.notify_all();
  16883. task_queue->shutdown();
  16884. }
  16885. TEST(TaskQueueTest, MaxQueuedRequests) {
  16886. static constexpr unsigned int qlimit{3};
  16887. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16888. std::condition_variable sem_cv;
  16889. std::mutex sem_mtx;
  16890. int credits = 0;
  16891. bool queued;
  16892. /* Fill up the queue with tasks that will block until we give them credits to
  16893. * complete. */
  16894. for (unsigned int n = 0; n <= qlimit;) {
  16895. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16896. std::unique_lock<std::mutex> lock(sem_mtx);
  16897. while (credits <= 0) {
  16898. sem_cv.wait(lock);
  16899. }
  16900. /* Consume the credit and signal the test code if they are all gone. */
  16901. if (--credits == 0) { sem_cv.notify_one(); }
  16902. });
  16903. if (n < qlimit) {
  16904. /* The first qlimit enqueues must succeed. */
  16905. EXPECT_TRUE(queued);
  16906. } else {
  16907. /* The last one will succeed only when the worker thread
  16908. * starts and dequeues the first blocking task. Although
  16909. * not necessary for the correctness of this test, we sleep for
  16910. * a short while to avoid busy waiting. */
  16911. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16912. }
  16913. if (queued) { n++; }
  16914. }
  16915. /* Further enqueues must fail since the queue is full. */
  16916. for (auto i = 0; i < 4; i++) {
  16917. queued = task_queue->enqueue([] {});
  16918. EXPECT_FALSE(queued);
  16919. }
  16920. /* Give the credits to allow the previous tasks to complete. */
  16921. {
  16922. std::unique_lock<std::mutex> lock(sem_mtx);
  16923. credits += qlimit + 1;
  16924. }
  16925. sem_cv.notify_all();
  16926. /* Wait for all the credits to be consumed. */
  16927. {
  16928. std::unique_lock<std::mutex> lock(sem_mtx);
  16929. while (credits > 0) {
  16930. sem_cv.wait(lock);
  16931. }
  16932. }
  16933. /* Check that we are able again to enqueue at least qlimit tasks. */
  16934. for (unsigned int i = 0; i < qlimit; i++) {
  16935. queued = task_queue->enqueue([] {});
  16936. EXPECT_TRUE(queued);
  16937. }
  16938. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16939. task_queue->shutdown();
  16940. #else
  16941. EXPECT_NO_THROW(task_queue->shutdown());
  16942. #endif
  16943. }
  16944. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16945. Server svr;
  16946. std::string method;
  16947. std::string body;
  16948. auto has_content_length = false;
  16949. auto has_transfer_encoding = false;
  16950. std::atomic<int> bad_requests{0};
  16951. // Leftover body bytes get parsed as a malformed request and answered with
  16952. // 400
  16953. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16954. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16955. });
  16956. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16957. res.set_redirect("/down", StatusCode::SeeOther_303);
  16958. });
  16959. svr.Get("/down", [&](const Request &req, Response &res) {
  16960. method = req.method;
  16961. body = req.body;
  16962. has_content_length = req.has_header("Content-Length");
  16963. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16964. res.set_content("ok", "text/plain");
  16965. });
  16966. auto port = svr.bind_to_any_port(HOST);
  16967. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16968. auto se = detail::scope_exit([&] {
  16969. svr.stop();
  16970. thread.join();
  16971. ASSERT_FALSE(svr.is_running());
  16972. });
  16973. svr.wait_until_ready();
  16974. const std::string payload = "SECRET-BODY";
  16975. auto check = [&](Client &cli, const Result &res) {
  16976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16977. EXPECT_EQ(StatusCode::OK_200, res->status);
  16978. EXPECT_EQ("ok", res->body);
  16979. EXPECT_EQ("GET", method);
  16980. EXPECT_TRUE(body.empty());
  16981. EXPECT_FALSE(has_content_length);
  16982. EXPECT_FALSE(has_transfer_encoding);
  16983. // Nothing of the original body may be left on the connection
  16984. auto res2 = cli.Get("/down");
  16985. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16986. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16987. EXPECT_EQ("ok", res2->body);
  16988. EXPECT_EQ(0, bad_requests);
  16989. };
  16990. // With content length
  16991. {
  16992. Client cli(HOST, port);
  16993. cli.set_keep_alive(true);
  16994. cli.set_follow_location(true);
  16995. auto res = cli.Post(
  16996. "/up", payload.size(),
  16997. [&](size_t offset, size_t length, DataSink &sink) {
  16998. return sink.write(payload.data() + offset, length);
  16999. },
  17000. "text/plain");
  17001. check(cli, res);
  17002. }
  17003. // Without content length (chunked)
  17004. {
  17005. Client cli(HOST, port);
  17006. cli.set_keep_alive(true);
  17007. cli.set_follow_location(true);
  17008. auto res = cli.Post(
  17009. "/up",
  17010. [&](size_t /*offset*/, DataSink &sink) {
  17011. sink.write(payload.data(), payload.size());
  17012. sink.done();
  17013. return true;
  17014. },
  17015. "text/plain");
  17016. check(cli, res);
  17017. }
  17018. }
  17019. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17020. Server svr;
  17021. std::string target;
  17022. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17023. // Echo the still-encoded name back in the Location
  17024. const std::string prefix = "/start/";
  17025. res.status = StatusCode::Found_302;
  17026. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17027. });
  17028. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17029. target = req.target;
  17030. res.set_content("ok", "text/plain");
  17031. });
  17032. auto port = svr.bind_to_any_port(HOST);
  17033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17034. auto se = detail::scope_exit([&] {
  17035. svr.stop();
  17036. thread.join();
  17037. ASSERT_FALSE(svr.is_running());
  17038. });
  17039. svr.wait_until_ready();
  17040. // Decoding the Location path would turn the first four into a path
  17041. // separator, a query delimiter, a fragment delimiter and a different
  17042. // percent-encoded octet. The rest must keep reaching the server as they are.
  17043. const std::vector<std::string> names = {
  17044. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17045. };
  17046. for (auto path_encode : {true, false}) {
  17047. Client cli(HOST, port);
  17048. cli.set_follow_location(true);
  17049. cli.set_path_encode(path_encode);
  17050. for (const auto &name : names) {
  17051. target.clear();
  17052. auto res = cli.Get("/start/" + name);
  17053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17054. EXPECT_EQ(StatusCode::OK_200, res->status);
  17055. EXPECT_EQ("/dest/" + name, target);
  17056. }
  17057. }
  17058. }
  17059. TEST(RedirectTest, NotModifiedIsReturned) {
  17060. Server svr;
  17061. svr.Get("/cached", [](const Request &, Response &res) {
  17062. res.status = StatusCode::NotModified_304;
  17063. });
  17064. auto port = svr.bind_to_any_port(HOST);
  17065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17066. auto se = detail::scope_exit([&] {
  17067. svr.stop();
  17068. thread.join();
  17069. ASSERT_FALSE(svr.is_running());
  17070. });
  17071. svr.wait_until_ready();
  17072. Client cli(HOST, port);
  17073. cli.set_follow_location(true);
  17074. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17076. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17077. }
  17078. TEST(RedirectTest, NoLocationIsReturned) {
  17079. Server svr;
  17080. svr.Get("/no-location", [](const Request &, Response &res) {
  17081. res.status = StatusCode::Found_302;
  17082. res.set_content("no location", "text/plain");
  17083. });
  17084. auto port = svr.bind_to_any_port(HOST);
  17085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17086. auto se = detail::scope_exit([&] {
  17087. svr.stop();
  17088. thread.join();
  17089. ASSERT_FALSE(svr.is_running());
  17090. });
  17091. svr.wait_until_ready();
  17092. Client cli(HOST, port);
  17093. cli.set_follow_location(true);
  17094. auto res = cli.Get("/no-location");
  17095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17096. EXPECT_EQ(StatusCode::Found_302, res->status);
  17097. EXPECT_EQ("no location", res->body);
  17098. // The callbacks see the body of the response that is returned
  17099. auto handler_called = false;
  17100. auto progress_called = false;
  17101. std::string body;
  17102. auto res2 = cli.Get(
  17103. "/no-location",
  17104. [&](const Response &) {
  17105. handler_called = true;
  17106. return true;
  17107. },
  17108. [&](const char *data, size_t data_length) {
  17109. body.append(data, data_length);
  17110. return true;
  17111. },
  17112. [&](size_t, size_t) {
  17113. progress_called = true;
  17114. return true;
  17115. });
  17116. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17117. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17118. EXPECT_TRUE(handler_called);
  17119. EXPECT_TRUE(progress_called);
  17120. EXPECT_EQ("no location", body);
  17121. }
  17122. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17123. Server svr;
  17124. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17125. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17126. });
  17127. svr.Get("/hello", [](const Request &req, Response &res) {
  17128. res.set_content(req.get_param_value("key"), "text/plain");
  17129. });
  17130. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17131. auto se = detail::scope_exit([&] {
  17132. svr.stop();
  17133. thread.join();
  17134. ASSERT_FALSE(svr.is_running());
  17135. });
  17136. svr.wait_until_ready();
  17137. {
  17138. Client cli(HOST, PORT);
  17139. cli.set_follow_location(true);
  17140. auto res = cli.Get("/");
  17141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17142. EXPECT_EQ(StatusCode::OK_200, res->status);
  17143. EXPECT_EQ("val&key2=val2", res->body);
  17144. }
  17145. }
  17146. #endif
  17147. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17148. Server svr;
  17149. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17150. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17151. });
  17152. svr.Get("/hello", [](const Request &req, Response &res) {
  17153. res.set_content(req.get_param_value("key"), "text/plain");
  17154. });
  17155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17156. auto se = detail::scope_exit([&] {
  17157. svr.stop();
  17158. thread.join();
  17159. ASSERT_FALSE(svr.is_running());
  17160. });
  17161. svr.wait_until_ready();
  17162. {
  17163. Client cli(HOST, PORT);
  17164. cli.set_follow_location(true);
  17165. auto res = cli.Get("/");
  17166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17167. EXPECT_EQ(StatusCode::OK_200, res->status);
  17168. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17169. }
  17170. }
  17171. TEST(RedirectTest, RedirectWithPlusInPath) {
  17172. Server svr;
  17173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17174. res.set_redirect("/a+b");
  17175. });
  17176. // Route pattern uses regex; escape + as \\+
  17177. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17178. res.set_content(req.path, "text/plain");
  17179. });
  17180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17181. auto se = detail::scope_exit([&] {
  17182. svr.stop();
  17183. thread.join();
  17184. ASSERT_FALSE(svr.is_running());
  17185. });
  17186. svr.wait_until_ready();
  17187. {
  17188. Client cli(HOST, PORT);
  17189. cli.set_follow_location(true);
  17190. auto res = cli.Get("/");
  17191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17192. EXPECT_EQ(StatusCode::OK_200, res->status);
  17193. EXPECT_EQ("/a+b", res->body);
  17194. }
  17195. }
  17196. TEST(RedirectTest, ResolveRelativeLocation) {
  17197. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17198. const std::vector<std::pair<std::string, std::string>> cases = {
  17199. {"g", "/b/c/g"},
  17200. {"./g", "/b/c/g"},
  17201. {"g/", "/b/c/g/"},
  17202. {"?y", "/b/c/d;p?y"},
  17203. {"g?y", "/b/c/g?y"},
  17204. {"#s", "/b/c/d;p?q#s"},
  17205. {"g#s", "/b/c/g#s"},
  17206. {"g?y#s", "/b/c/g?y#s"},
  17207. {";x", "/b/c/;x"},
  17208. {"g;x", "/b/c/g;x"},
  17209. {".", "/b/c/"},
  17210. {"./", "/b/c/"},
  17211. {"..", "/b/"},
  17212. {"../", "/b/"},
  17213. {"../g", "/b/g"},
  17214. {"../..", "/"},
  17215. {"../../", "/"},
  17216. {"../../g", "/g"},
  17217. {"../../../g", "/g"},
  17218. {"g.", "/b/c/g."},
  17219. {".g", "/b/c/.g"},
  17220. {"g..", "/b/c/g.."},
  17221. {"..g", "/b/c/..g"},
  17222. {"./../g", "/b/g"},
  17223. {"./g/.", "/b/c/g/"},
  17224. {"g/./h", "/b/c/g/h"},
  17225. {"g/../h", "/b/c/h"},
  17226. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17227. {"g;x=1/../y", "/b/c/y"},
  17228. {"g?y/./x", "/b/c/g?y/./x"},
  17229. {"g#s/../x", "/b/c/g#s/../x"},
  17230. // Not relative-path references, so left for parse_url.
  17231. {"/g", "/g"},
  17232. {"//g", "//g"},
  17233. {"http://g/x", "http://g/x"},
  17234. {"g:h", "g:h"},
  17235. };
  17236. for (const auto &c : cases) {
  17237. EXPECT_EQ(c.second,
  17238. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17239. << c.first;
  17240. }
  17241. }
  17242. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17243. Server svr;
  17244. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17245. res.set_redirect(req.get_param_value("to"));
  17246. });
  17247. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17248. res.set_content(req.target, "text/plain");
  17249. });
  17250. svr.Get("/other", [](const Request &req, Response &res) {
  17251. res.set_content(req.target, "text/plain");
  17252. });
  17253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17254. auto se = detail::scope_exit([&] {
  17255. svr.stop();
  17256. thread.join();
  17257. ASSERT_FALSE(svr.is_running());
  17258. });
  17259. svr.wait_until_ready();
  17260. const std::vector<std::pair<std::string, std::string>> cases = {
  17261. {"next", "/dir/next"},
  17262. {"./next?x=1", "/dir/next?x=1"},
  17263. {"../other", "/other"},
  17264. };
  17265. for (const auto &c : cases) {
  17266. Client cli(HOST, PORT);
  17267. cli.set_follow_location(true);
  17268. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17269. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17270. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17271. EXPECT_EQ(c.second, res->body) << c.first;
  17272. }
  17273. }
  17274. #ifdef CPPHTTPLIB_SSL_ENABLED
  17275. TEST(RedirectTest, Issue2185_Online) {
  17276. SSLClient client("github.com");
  17277. client.set_follow_location(true);
  17278. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17279. "Coollab-Windows.zip");
  17280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17281. EXPECT_EQ(StatusCode::OK_200, res->status);
  17282. EXPECT_EQ(9920427U, res->body.size());
  17283. }
  17284. #endif
  17285. TEST(VulnerabilityTest, CRLFInjection) {
  17286. Server svr;
  17287. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17288. res.set_content("Hello 1", "text/plain");
  17289. });
  17290. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17291. res.set_content("Hello 2", "text/plain");
  17292. });
  17293. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17294. res.set_content("Hello 3", "text/plain");
  17295. });
  17296. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17297. res.set_content("Hello 4", "text/plain");
  17298. });
  17299. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17300. for (const auto &x : req.headers) {
  17301. auto key = x.first;
  17302. EXPECT_STRNE("evil", key.c_str());
  17303. }
  17304. });
  17305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17306. auto se = detail::scope_exit([&] {
  17307. svr.stop();
  17308. thread.join();
  17309. ASSERT_FALSE(svr.is_running());
  17310. });
  17311. svr.wait_until_ready();
  17312. {
  17313. Client cli(HOST, PORT);
  17314. cli.Post("/test1", "A=B",
  17315. "application/x-www-form-urlencoded\r\nevil: hello1");
  17316. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17317. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17318. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17319. }
  17320. }
  17321. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17322. auto server_thread = std::thread([] {
  17323. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17324. default_socket_options(srv);
  17325. sockaddr_in addr{};
  17326. addr.sin_family = AF_INET;
  17327. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17328. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17329. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17330. ::listen(srv, 1);
  17331. sockaddr_in cli_addr{};
  17332. socklen_t cli_len = sizeof(cli_addr);
  17333. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17334. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17335. std::string buf_all;
  17336. char buf[2048];
  17337. ssize_t n;
  17338. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17339. buf_all.append(buf, static_cast<size_t>(n));
  17340. size_t pos;
  17341. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17342. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17343. auto e = request_block.find("\r\n");
  17344. if (e != std::string::npos) {
  17345. auto request_line = request_block.substr(0, e);
  17346. std::string msg =
  17347. "CRLF injection detected in request line: '" + request_line + "'";
  17348. EXPECT_FALSE(true) << msg;
  17349. }
  17350. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17351. ::send(cli,
  17352. #ifdef _WIN32
  17353. static_cast<const char *>(resp.c_str()),
  17354. static_cast<int>(resp.size()),
  17355. #else
  17356. resp.c_str(), resp.size(),
  17357. #endif
  17358. 0);
  17359. buf_all.erase(0, pos + 4);
  17360. }
  17361. }
  17362. detail::close_socket(cli);
  17363. detail::close_socket(srv);
  17364. });
  17365. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17366. auto cli = Client("127.0.0.1", PORT + 1);
  17367. auto headers = Headers{
  17368. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17369. {"Connection", "keep-alive"}};
  17370. auto res = cli.Get("/hi", headers);
  17371. EXPECT_FALSE(res);
  17372. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17373. server_thread.join();
  17374. }
  17375. // A request rejected before any byte reaches the socket must fail right away
  17376. // instead of waiting for a response the server will never send.
  17377. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17378. // The kernel completes the TCP handshake from the listen backlog, so the
  17379. // client connects, but nothing ever reads, responds or closes.
  17380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17381. default_socket_options(srv);
  17382. sockaddr_in addr{};
  17383. addr.sin_family = AF_INET;
  17384. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17385. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17386. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17387. ASSERT_EQ(0, ::listen(srv, 8));
  17388. auto cli = Client("127.0.0.1", PORT + 1);
  17389. cli.set_read_timeout(10, 0);
  17390. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17391. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17392. std::chrono::steady_clock::now() - start)
  17393. .count();
  17394. };
  17395. {
  17396. Request req;
  17397. req.method = "GE T";
  17398. req.path = "/";
  17399. auto start = std::chrono::steady_clock::now();
  17400. auto res = cli.send(req);
  17401. EXPECT_FALSE(res);
  17402. EXPECT_EQ(Error::Write, res.error());
  17403. EXPECT_LT(elapsed_ms(start), 1000);
  17404. }
  17405. {
  17406. auto start = std::chrono::steady_clock::now();
  17407. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17408. EXPECT_FALSE(res);
  17409. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17410. EXPECT_LT(elapsed_ms(start), 1000);
  17411. }
  17412. EXPECT_FALSE(cli.is_socket_open());
  17413. detail::close_socket(srv);
  17414. }
  17415. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17416. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17417. default_socket_options(srv);
  17418. sockaddr_in addr{};
  17419. addr.sin_family = AF_INET;
  17420. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17421. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17422. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17423. ASSERT_EQ(0, ::listen(srv, 1));
  17424. std::string received;
  17425. auto server_thread = std::thread([&] {
  17426. auto sock = ::accept(srv, nullptr, nullptr);
  17427. if (sock == INVALID_SOCKET) { return; }
  17428. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17429. char buf[2048];
  17430. ssize_t n;
  17431. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17432. received.append(buf, static_cast<size_t>(n));
  17433. }
  17434. detail::close_socket(sock);
  17435. });
  17436. {
  17437. auto cli = Client("127.0.0.1", PORT + 1);
  17438. // "Z" sorts after the default headers, so writing straight to the socket
  17439. // would have sent the request line and those headers before the rejection.
  17440. auto handle =
  17441. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17442. EXPECT_FALSE(handle.is_valid());
  17443. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17444. }
  17445. server_thread.join();
  17446. detail::close_socket(srv);
  17447. EXPECT_TRUE(received.empty()) << received;
  17448. }
  17449. TEST(PathParamsTest, StaticMatch) {
  17450. const auto pattern = "/users/all";
  17451. detail::PathParamsMatcher matcher(pattern);
  17452. Request request;
  17453. request.path = "/users/all";
  17454. ASSERT_TRUE(matcher.match(request));
  17455. std::unordered_map<std::string, std::string> expected_params = {};
  17456. EXPECT_EQ(request.path_params, expected_params);
  17457. }
  17458. TEST(PathParamsTest, StaticMismatch) {
  17459. const auto pattern = "/users/all";
  17460. detail::PathParamsMatcher matcher(pattern);
  17461. Request request;
  17462. request.path = "/users/1";
  17463. ASSERT_FALSE(matcher.match(request));
  17464. }
  17465. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17466. const auto pattern = "/users/:id/subscriptions";
  17467. detail::PathParamsMatcher matcher(pattern);
  17468. Request request;
  17469. request.path = "/users/42/subscriptions";
  17470. ASSERT_TRUE(matcher.match(request));
  17471. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17472. EXPECT_EQ(request.path_params, expected_params);
  17473. }
  17474. TEST(PathParamsTest, SingleParamInTheEnd) {
  17475. const auto pattern = "/users/:id";
  17476. detail::PathParamsMatcher matcher(pattern);
  17477. Request request;
  17478. request.path = "/users/24";
  17479. ASSERT_TRUE(matcher.match(request));
  17480. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17481. EXPECT_EQ(request.path_params, expected_params);
  17482. }
  17483. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17484. const auto pattern = "/users/:id/";
  17485. detail::PathParamsMatcher matcher(pattern);
  17486. Request request;
  17487. request.path = "/users/42/";
  17488. ASSERT_TRUE(matcher.match(request));
  17489. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17490. EXPECT_EQ(request.path_params, expected_params);
  17491. }
  17492. TEST(PathParamsTest, EmptyParam) {
  17493. const auto pattern = "/users/:id/";
  17494. detail::PathParamsMatcher matcher(pattern);
  17495. Request request;
  17496. request.path = "/users//";
  17497. ASSERT_TRUE(matcher.match(request));
  17498. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17499. EXPECT_EQ(request.path_params, expected_params);
  17500. }
  17501. TEST(PathParamsTest, FragmentMismatch) {
  17502. const auto pattern = "/users/:id/";
  17503. detail::PathParamsMatcher matcher(pattern);
  17504. Request request;
  17505. request.path = "/admins/24/";
  17506. ASSERT_FALSE(matcher.match(request));
  17507. }
  17508. TEST(PathParamsTest, ExtraFragments) {
  17509. const auto pattern = "/users/:id";
  17510. detail::PathParamsMatcher matcher(pattern);
  17511. Request request;
  17512. request.path = "/users/42/subscriptions";
  17513. ASSERT_FALSE(matcher.match(request));
  17514. }
  17515. TEST(PathParamsTest, MissingTrailingParam) {
  17516. const auto pattern = "/users/:id";
  17517. detail::PathParamsMatcher matcher(pattern);
  17518. Request request;
  17519. request.path = "/users";
  17520. ASSERT_FALSE(matcher.match(request));
  17521. }
  17522. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17523. const auto pattern = "/users/:id/subscriptions";
  17524. detail::PathParamsMatcher matcher(pattern);
  17525. Request request;
  17526. request.path = "/users/subscriptions";
  17527. ASSERT_FALSE(matcher.match(request));
  17528. }
  17529. TEST(PathParamsTest, MultipleParams) {
  17530. const auto pattern = "/users/:userid/subscriptions/:subid";
  17531. detail::PathParamsMatcher matcher(pattern);
  17532. Request request;
  17533. request.path = "/users/42/subscriptions/2";
  17534. ASSERT_TRUE(matcher.match(request));
  17535. std::unordered_map<std::string, std::string> expected_params = {
  17536. {"userid", "42"}, {"subid", "2"}};
  17537. EXPECT_EQ(request.path_params, expected_params);
  17538. }
  17539. TEST(PathParamsTest, SequenceOfParams) {
  17540. const auto pattern = "/values/:x/:y/:z";
  17541. detail::PathParamsMatcher matcher(pattern);
  17542. Request request;
  17543. request.path = "/values/1/2/3";
  17544. ASSERT_TRUE(matcher.match(request));
  17545. std::unordered_map<std::string, std::string> expected_params = {
  17546. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17547. EXPECT_EQ(request.path_params, expected_params);
  17548. }
  17549. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17550. const auto pattern = "/prefix:suffix";
  17551. detail::PathParamsMatcher matcher(pattern);
  17552. Request request;
  17553. request.path = "/prefix:suffix";
  17554. ASSERT_TRUE(matcher.match(request));
  17555. const std::unordered_map<std::string, std::string> expected_params = {};
  17556. EXPECT_EQ(request.path_params, expected_params);
  17557. }
  17558. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17559. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17560. // calling thread's stack on a long enough path for a quantified pattern;
  17561. // RegexMatcher must refuse to run regex matching on paths beyond
  17562. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17563. detail::RegexMatcher matcher("/files/(.*)");
  17564. Request within_limit;
  17565. within_limit.path = "/files/" + std::string(10, 'A');
  17566. EXPECT_TRUE(matcher.match(within_limit));
  17567. Request over_limit;
  17568. over_limit.path =
  17569. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17570. EXPECT_FALSE(matcher.match(over_limit));
  17571. }
  17572. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17573. Server svr;
  17574. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17575. res.set_content("ok", "text/plain");
  17576. });
  17577. auto port = svr.bind_to_any_port(HOST);
  17578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17579. auto se = detail::scope_exit([&] {
  17580. svr.stop();
  17581. thread.join();
  17582. ASSERT_FALSE(svr.is_running());
  17583. });
  17584. svr.wait_until_ready();
  17585. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17586. // request URI limit; this used to be able to crash the process.
  17587. std::string path =
  17588. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17589. std::string req = "GET " + path +
  17590. " HTTP/1.1\r\n"
  17591. "Host: " +
  17592. std::string(HOST) + ":" + std::to_string(port) +
  17593. "\r\n"
  17594. "Connection: close\r\n"
  17595. "\r\n";
  17596. std::string response;
  17597. ASSERT_TRUE(send_request(5, req, &response, port));
  17598. EXPECT_NE(std::string::npos, response.find("404"));
  17599. }
  17600. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17601. Server svr;
  17602. auto handler = [](const Request & /*req*/, Response &res) {
  17603. res.set_content("hit", "text/plain");
  17604. };
  17605. // No regex metacharacter, so this one is compared literally
  17606. svr.Get("/literal/route", handler);
  17607. // '.' is a regex metacharacter, so this one must keep regex semantics
  17608. svr.Get("/a.c", handler);
  17609. auto port = svr.bind_to_any_port(HOST);
  17610. std::thread t([&]() { svr.listen_after_bind(); });
  17611. auto se = detail::scope_exit([&] {
  17612. svr.stop();
  17613. t.join();
  17614. ASSERT_FALSE(svr.is_running());
  17615. });
  17616. svr.wait_until_ready();
  17617. Client cli(HOST, port);
  17618. struct {
  17619. const char *path;
  17620. int status;
  17621. } cases[] = {
  17622. {"/literal/route", StatusCode::OK_200},
  17623. {"/literal/routes", StatusCode::NotFound_404},
  17624. {"/literal/rout", StatusCode::NotFound_404},
  17625. {"/abc", StatusCode::OK_200},
  17626. {"/a.c", StatusCode::OK_200},
  17627. };
  17628. for (const auto &x : cases) {
  17629. auto res = cli.Get(x.path);
  17630. ASSERT_TRUE(res) << x.path;
  17631. EXPECT_EQ(x.status, res->status) << x.path;
  17632. }
  17633. }
  17634. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17635. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17636. // from exhausting the stack, so it must only constrain routes that actually
  17637. // run a regular expression. A literal route is matched by comparison and
  17638. // stays usable at any length.
  17639. Server svr;
  17640. const std::string pattern =
  17641. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17642. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17643. res.set_content("hit", "text/plain");
  17644. });
  17645. auto port = svr.bind_to_any_port(HOST);
  17646. std::thread t([&]() { svr.listen_after_bind(); });
  17647. auto se = detail::scope_exit([&] {
  17648. svr.stop();
  17649. t.join();
  17650. ASSERT_FALSE(svr.is_running());
  17651. });
  17652. svr.wait_until_ready();
  17653. Client cli(HOST, port);
  17654. auto res = cli.Get(pattern);
  17655. ASSERT_TRUE(res);
  17656. EXPECT_EQ(StatusCode::OK_200, res->status);
  17657. }
  17658. TEST(ParseUrlTest, VariousPatterns) {
  17659. {
  17660. detail::UrlComponents uc;
  17661. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17662. EXPECT_EQ("http", uc.scheme);
  17663. EXPECT_EQ("example.com", uc.host);
  17664. EXPECT_EQ("8080", uc.port);
  17665. EXPECT_EQ("/path", uc.path);
  17666. EXPECT_EQ("?q=1", uc.query);
  17667. }
  17668. {
  17669. detail::UrlComponents uc;
  17670. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17671. EXPECT_EQ("https", uc.scheme);
  17672. EXPECT_EQ("example.com", uc.host);
  17673. EXPECT_TRUE(uc.port.empty());
  17674. EXPECT_EQ("/path", uc.path);
  17675. }
  17676. {
  17677. detail::UrlComponents uc;
  17678. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17679. EXPECT_EQ("::1", uc.host);
  17680. EXPECT_EQ("8080", uc.port);
  17681. EXPECT_EQ("/path", uc.path);
  17682. }
  17683. {
  17684. detail::UrlComponents uc;
  17685. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17686. }
  17687. {
  17688. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17689. // the path while the connection still targets the bracketed host.
  17690. detail::UrlComponents uc;
  17691. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17692. }
  17693. {
  17694. detail::UrlComponents uc;
  17695. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17696. }
  17697. {
  17698. detail::UrlComponents uc;
  17699. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17700. EXPECT_EQ("::1", uc.host);
  17701. EXPECT_TRUE(uc.port.empty());
  17702. EXPECT_EQ("/path", uc.path);
  17703. }
  17704. {
  17705. detail::UrlComponents uc;
  17706. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17707. EXPECT_TRUE(uc.scheme.empty());
  17708. EXPECT_EQ("example.com", uc.host);
  17709. EXPECT_EQ("/path", uc.path);
  17710. EXPECT_EQ("?q=1", uc.query);
  17711. }
  17712. {
  17713. detail::UrlComponents uc;
  17714. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17715. EXPECT_TRUE(uc.host.empty());
  17716. EXPECT_EQ("/path", uc.path);
  17717. EXPECT_EQ("?q=1", uc.query);
  17718. }
  17719. {
  17720. detail::UrlComponents uc;
  17721. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17722. EXPECT_EQ("example.com", uc.host);
  17723. EXPECT_EQ("8080", uc.port);
  17724. }
  17725. {
  17726. // Unix socket path — must not be parsed as host
  17727. detail::UrlComponents uc;
  17728. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17729. EXPECT_TRUE(uc.host.empty());
  17730. }
  17731. {
  17732. detail::UrlComponents uc;
  17733. ASSERT_TRUE(detail::parse_url("", uc));
  17734. EXPECT_TRUE(uc.host.empty());
  17735. EXPECT_TRUE(uc.path.empty());
  17736. }
  17737. {
  17738. detail::UrlComponents uc;
  17739. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17740. }
  17741. {
  17742. detail::UrlComponents uc;
  17743. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17744. }
  17745. {
  17746. // Accepted by parse_url; callers restrict to http/https
  17747. detail::UrlComponents uc;
  17748. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17749. EXPECT_EQ("ftp", uc.scheme);
  17750. }
  17751. {
  17752. detail::UrlComponents uc;
  17753. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17754. }
  17755. {
  17756. detail::UrlComponents uc;
  17757. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17758. }
  17759. }
  17760. TEST(ParseUrlTest, FragmentHandling) {
  17761. {
  17762. detail::UrlComponents uc;
  17763. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17764. EXPECT_EQ("/path", uc.path);
  17765. EXPECT_TRUE(uc.query.empty());
  17766. }
  17767. {
  17768. detail::UrlComponents uc;
  17769. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17770. EXPECT_TRUE(uc.path.empty());
  17771. EXPECT_TRUE(uc.query.empty());
  17772. }
  17773. }
  17774. TEST(ParseUrlTest, UserinfoHandling) {
  17775. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17776. // parsers would see evil.com as the host.
  17777. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17778. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17779. for (auto url : urls) {
  17780. detail::UrlComponents uc;
  17781. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17782. }
  17783. }
  17784. TEST(ParseUrlTest, IPv6EdgeCases) {
  17785. {
  17786. detail::UrlComponents uc;
  17787. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17788. EXPECT_TRUE(uc.scheme.empty());
  17789. EXPECT_EQ("::1", uc.host);
  17790. EXPECT_EQ("8080", uc.port);
  17791. }
  17792. {
  17793. // Zone ID '%25' is not in [a-fA-F0-9:]
  17794. detail::UrlComponents uc;
  17795. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17796. }
  17797. }
  17798. TEST(ParseUrlTest, SchemeEdgeCases) {
  17799. {
  17800. detail::UrlComponents uc;
  17801. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17802. }
  17803. {
  17804. detail::UrlComponents uc;
  17805. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17806. }
  17807. {
  17808. detail::UrlComponents uc;
  17809. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17810. }
  17811. }
  17812. TEST(ParseUrlTest, PortEdgeCases) {
  17813. {
  17814. detail::UrlComponents uc;
  17815. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17816. EXPECT_TRUE(uc.port.empty());
  17817. EXPECT_EQ("/path", uc.path);
  17818. }
  17819. {
  17820. // parse_url accepts any port string; validation is done by parse_port
  17821. detail::UrlComponents uc;
  17822. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17823. EXPECT_EQ("abc", uc.port);
  17824. }
  17825. }
  17826. TEST(ParseUrlTest, WebSocketPatterns) {
  17827. {
  17828. detail::UrlComponents uc;
  17829. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17830. EXPECT_EQ("ws", uc.scheme);
  17831. EXPECT_EQ("echo.example.com", uc.host);
  17832. EXPECT_EQ("8080", uc.port);
  17833. EXPECT_EQ("/ws", uc.path);
  17834. }
  17835. {
  17836. detail::UrlComponents uc;
  17837. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17838. EXPECT_EQ("wss", uc.scheme);
  17839. EXPECT_EQ("echo.example.com", uc.host);
  17840. EXPECT_TRUE(uc.port.empty());
  17841. EXPECT_EQ("/ws", uc.path);
  17842. }
  17843. }
  17844. TEST(ParseUrlTest, QueryOnly) {
  17845. detail::UrlComponents uc;
  17846. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17847. EXPECT_TRUE(uc.host.empty());
  17848. EXPECT_TRUE(uc.path.empty());
  17849. EXPECT_EQ("?q=1&r=2", uc.query);
  17850. }
  17851. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17852. detail::UrlComponents uc;
  17853. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17854. EXPECT_TRUE(uc.scheme.empty());
  17855. EXPECT_EQ("example.com", uc.host);
  17856. EXPECT_EQ("443", uc.port);
  17857. EXPECT_EQ("/path", uc.path);
  17858. }
  17859. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17860. // If ipv6 regex working, regex match codepath is taken.
  17861. // else port will default to 80 in Client impl
  17862. int clientImplMagicPort = 80;
  17863. int port = 4321;
  17864. // above ports must be different to avoid false negative
  17865. EXPECT_NE(clientImplMagicPort, port);
  17866. std::string ipV6TestURL = "http://[ff06::c3]";
  17867. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17868. CLIENT_PRIVATE_KEY_FILE);
  17869. EXPECT_EQ(cli.port(), port);
  17870. }
  17871. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17872. auto file_path = "./www/dir/index.html";
  17873. auto dir_path = "./www/dir";
  17874. detail::FileStat stat_file(file_path);
  17875. EXPECT_TRUE(stat_file.is_file());
  17876. EXPECT_FALSE(stat_file.is_dir());
  17877. detail::FileStat stat_dir(dir_path);
  17878. EXPECT_FALSE(stat_dir.is_file());
  17879. EXPECT_TRUE(stat_dir.is_dir());
  17880. }
  17881. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17882. // IPv4 with default HTTP port (80)
  17883. EXPECT_EQ("example.com",
  17884. detail::make_host_and_port_string("example.com", 80, false));
  17885. // IPv4 with default HTTPS port (443)
  17886. EXPECT_EQ("example.com",
  17887. detail::make_host_and_port_string("example.com", 443, true));
  17888. // IPv4 with non-default HTTP port
  17889. EXPECT_EQ("example.com:8080",
  17890. detail::make_host_and_port_string("example.com", 8080, false));
  17891. // IPv4 with non-default HTTPS port
  17892. EXPECT_EQ("example.com:8443",
  17893. detail::make_host_and_port_string("example.com", 8443, true));
  17894. // IPv6 with default HTTP port (80)
  17895. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17896. // IPv6 with default HTTPS port (443)
  17897. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17898. // IPv6 with non-default HTTP port
  17899. EXPECT_EQ("[::1]:8080",
  17900. detail::make_host_and_port_string("::1", 8080, false));
  17901. // IPv6 with non-default HTTPS port
  17902. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17903. // IPv6 full address with default port
  17904. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17905. detail::make_host_and_port_string(
  17906. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17907. // IPv6 full address with non-default port
  17908. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17909. detail::make_host_and_port_string(
  17910. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17911. // IPv6 localhost with non-default port
  17912. EXPECT_EQ("[::1]:3000",
  17913. detail::make_host_and_port_string("::1", 3000, false));
  17914. // IPv6 with zone ID (link-local address) with default port
  17915. EXPECT_EQ("[fe80::1%eth0]",
  17916. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17917. // IPv6 with zone ID (link-local address) with non-default port
  17918. EXPECT_EQ("[fe80::1%eth0]:8080",
  17919. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17920. // Edge case: Port 443 with is_ssl=false (should add port)
  17921. EXPECT_EQ("example.com:443",
  17922. detail::make_host_and_port_string("example.com", 443, false));
  17923. // Edge case: Port 80 with is_ssl=true (should add port)
  17924. EXPECT_EQ("example.com:80",
  17925. detail::make_host_and_port_string("example.com", 80, true));
  17926. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17927. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17928. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17929. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17930. // Security fix: Already bracketed IPv6 should not get double brackets
  17931. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17932. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17933. EXPECT_EQ("[::1]:8080",
  17934. detail::make_host_and_port_string("[::1]", 8080, false));
  17935. EXPECT_EQ("[2001:db8::1]:8080",
  17936. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17937. EXPECT_EQ("[fe80::1%eth0]",
  17938. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17939. EXPECT_EQ("[fe80::1%eth0]:8080",
  17940. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17941. // Edge case: Empty host (should return as-is)
  17942. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17943. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17944. // This is a known limitation but shouldn't crash
  17945. EXPECT_EQ("[host:name]",
  17946. detail::make_host_and_port_string("host:name", 80, false));
  17947. // Port number edge cases (no validation, but should not crash)
  17948. EXPECT_EQ("example.com:0",
  17949. detail::make_host_and_port_string("example.com", 0, false));
  17950. EXPECT_EQ("example.com:-1",
  17951. detail::make_host_and_port_string("example.com", -1, false));
  17952. EXPECT_EQ("example.com:65535",
  17953. detail::make_host_and_port_string("example.com", 65535, false));
  17954. EXPECT_EQ("example.com:65536",
  17955. detail::make_host_and_port_string("example.com", 65536, false));
  17956. }
  17957. #ifdef CPPHTTPLIB_SSL_ENABLED
  17958. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17959. httplib::SSLClient cli("roblox.com", 443);
  17960. cli.set_follow_location(true);
  17961. auto res = cli.Get("/");
  17962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17963. EXPECT_EQ(StatusCode::OK_200, res->status);
  17964. }
  17965. #endif
  17966. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17967. Server svr;
  17968. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17969. EXPECT_EQ(res.status, 400);
  17970. });
  17971. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17972. auto se = detail::scope_exit([&] {
  17973. svr.stop();
  17974. thread.join();
  17975. ASSERT_FALSE(svr.is_running());
  17976. });
  17977. svr.wait_until_ready();
  17978. Client cli(HOST, PORT);
  17979. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17980. }
  17981. TEST(InvalidHeaderCharsTest, is_field_name) {
  17982. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17983. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17984. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17985. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17986. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17987. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17988. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17989. EXPECT_FALSE(detail::fields::is_field_name(""));
  17990. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17991. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17992. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17993. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17994. }
  17995. TEST(InvalidHeaderCharsTest, is_field_value) {
  17996. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17997. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17998. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17999. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18000. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18001. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18002. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18003. EXPECT_TRUE(detail::fields::is_field_value(""));
  18004. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18005. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18006. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18007. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18008. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18009. }
  18010. TEST(InvalidHeaderCharsTest, OnServer) {
  18011. Server svr;
  18012. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18013. std::string header = "Not Set";
  18014. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18015. res.set_header(header, "value");
  18016. res.set_content("Page Content Page Content", "text/plain");
  18017. });
  18018. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18019. std::string header = "Not Set";
  18020. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18021. res.set_header("X-Test", header);
  18022. res.set_content("Page Content Page Content", "text/plain");
  18023. });
  18024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18025. auto se = detail::scope_exit([&] {
  18026. svr.stop();
  18027. thread.join();
  18028. ASSERT_FALSE(svr.is_running());
  18029. });
  18030. svr.wait_until_ready();
  18031. Client cli(HOST, PORT);
  18032. {
  18033. auto res = cli.Get(
  18034. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18036. EXPECT_EQ("Page Content Page Content", res->body);
  18037. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18038. }
  18039. {
  18040. auto res = cli.Get(
  18041. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18043. EXPECT_EQ("Page Content Page Content", res->body);
  18044. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18045. }
  18046. }
  18047. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18048. auto handled = false;
  18049. Server svr;
  18050. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18051. thread t = thread([&] { svr.listen(HOST, PORT); });
  18052. auto se = detail::scope_exit([&] {
  18053. svr.stop();
  18054. t.join();
  18055. ASSERT_FALSE(svr.is_running());
  18056. ASSERT_FALSE(handled);
  18057. });
  18058. svr.wait_until_ready();
  18059. auto req = "POST /test HTTP/1.1\r\n"
  18060. "Content-Length: x\r\n"
  18061. "\r\n";
  18062. std::string response;
  18063. ASSERT_TRUE(send_request(1, req, &response));
  18064. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18065. response.substr(0, response.find("\r\n")));
  18066. }
  18067. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18068. // case-insensitive, and a server that receives a 100-continue expectation in
  18069. // an HTTP/1.0 request MUST ignore it.
  18070. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18071. std::string response;
  18072. ASSERT_TRUE(send_request(1, req, &response, port));
  18073. *got_100 = response.find("100 Continue") != std::string::npos;
  18074. }
  18075. class ExpectTokenTest : public ::testing::Test {
  18076. protected:
  18077. void SetUp() override {
  18078. svr_.Post("/p", [](const Request &, Response &res) {
  18079. res.set_content("ok", "text/plain");
  18080. });
  18081. port_ = svr_.bind_to_any_port(HOST);
  18082. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18083. svr_.wait_until_ready();
  18084. }
  18085. void TearDown() override {
  18086. svr_.stop();
  18087. if (thread_.joinable()) { thread_.join(); }
  18088. }
  18089. std::string request(const char *version, const char *expect_value) const {
  18090. return std::string("POST /p ") + version +
  18091. "\r\n"
  18092. "Host: localhost\r\n"
  18093. "Content-Length: 2\r\n"
  18094. "Connection: close\r\n"
  18095. "Expect: " +
  18096. expect_value +
  18097. "\r\n"
  18098. "\r\n"
  18099. "hi";
  18100. }
  18101. Server svr_;
  18102. int port_ = 0;
  18103. thread thread_;
  18104. };
  18105. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18106. bool got_100 = false;
  18107. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18108. EXPECT_TRUE(got_100);
  18109. }
  18110. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18111. bool got_100 = true;
  18112. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18113. EXPECT_FALSE(got_100);
  18114. }
  18115. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18116. bool got_100 = false;
  18117. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18118. EXPECT_TRUE(got_100);
  18119. }
  18120. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18121. bool got_100 = false;
  18122. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18123. EXPECT_TRUE(got_100);
  18124. }
  18125. // `100 Continue` is sent only when the server starts reading the body, so a
  18126. // request rejected before that never invites the client to send it. The
  18127. // requests below carry the expectation but withhold the body, as a client
  18128. // waiting for `100 Continue` would.
  18129. // A POST that expects `100 Continue` and withholds its two-byte body.
  18130. static std::string expect_headers_only(const std::string &path) {
  18131. return "POST " + path +
  18132. " HTTP/1.1\r\n"
  18133. "Host: localhost\r\n"
  18134. "Content-Length: 2\r\n"
  18135. "Expect: 100-continue\r\n"
  18136. "\r\n";
  18137. }
  18138. class ExpectLazyContinueTest : public ::testing::Test {
  18139. protected:
  18140. void SetUp() override {
  18141. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18142. if (req.path == "/pre-routing") {
  18143. res.status = StatusCode::Unauthorized_401;
  18144. return Server::HandlerResponse::Handled;
  18145. }
  18146. return Server::HandlerResponse::Unhandled;
  18147. });
  18148. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18149. if (req.matched_route == "/pre-request") {
  18150. res.status = StatusCode::Forbidden_403;
  18151. return Server::HandlerResponse::Handled;
  18152. }
  18153. return Server::HandlerResponse::Unhandled;
  18154. });
  18155. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18156. res.set_content("ok", "text/plain");
  18157. });
  18158. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18159. res.set_content("ok", "text/plain");
  18160. });
  18161. svr_.Post("/reader-used", [](const Request &, Response &res,
  18162. const ContentReader &content_reader) {
  18163. std::string body;
  18164. content_reader([&](const char *data, size_t len) {
  18165. body.append(data, len);
  18166. return true;
  18167. });
  18168. res.set_content(body, "text/plain");
  18169. });
  18170. svr_.Post("/reader-unused",
  18171. [](const Request &, Response &res, const ContentReader &) {
  18172. res.set_content("ignored", "text/plain");
  18173. });
  18174. port_ = svr_.bind_to_any_port(HOST);
  18175. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18176. svr_.wait_until_ready();
  18177. }
  18178. void TearDown() override {
  18179. svr_.stop();
  18180. if (thread_.joinable()) { thread_.join(); }
  18181. }
  18182. // Sends `req` and reads until the server closes the connection. Returns
  18183. // false if the read had to wait for the client-side timeout instead.
  18184. bool send_until_closed(const std::string &req, std::string *resp) const {
  18185. auto start = std::chrono::steady_clock::now();
  18186. if (!send_request(3, req, resp, port_)) { return false; }
  18187. auto elapsed = std::chrono::steady_clock::now() - start;
  18188. return elapsed < std::chrono::seconds(2);
  18189. }
  18190. // The final response comes without `100 Continue`, and the server closes
  18191. // the connection since the body may or may not follow.
  18192. void expect_final_without_interim(const std::string &path,
  18193. const char *status_line) const {
  18194. std::string resp;
  18195. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18196. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18197. EXPECT_EQ(0u, resp.find(status_line));
  18198. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18199. }
  18200. Server svr_;
  18201. int port_ = 0;
  18202. thread thread_;
  18203. };
  18204. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18205. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18206. }
  18207. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18208. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18209. }
  18210. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18211. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18212. }
  18213. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18214. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18215. }
  18216. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18217. // The body follows once `100 Continue` has had time to arrive.
  18218. auto req = expect_headers_only("/reader-used");
  18219. req.insert(req.size() - 2, "Connection: close\r\n");
  18220. std::string resp;
  18221. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18222. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18223. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18224. EXPECT_NE(std::string::npos, resp.find("hi"));
  18225. }
  18226. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18227. // Large enough for the client to add `Expect: 100-continue` itself.
  18228. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18229. std::atomic<bool> body_sent{false};
  18230. Client cli(HOST, port_);
  18231. auto res = cli.Post(
  18232. "/pre-request", length,
  18233. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18234. body_sent = true;
  18235. std::string chunk(len, 'x');
  18236. sink.write(chunk.data(), chunk.size());
  18237. return true;
  18238. },
  18239. "application/octet-stream");
  18240. ASSERT_TRUE(res);
  18241. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18242. EXPECT_FALSE(body_sent);
  18243. }
  18244. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18245. Server svr;
  18246. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18247. return StatusCode::ExpectationFailed_417;
  18248. });
  18249. svr.Post("/p", [](const Request &, Response &res) {
  18250. res.set_content("ok", "text/plain");
  18251. });
  18252. auto port = svr.bind_to_any_port(HOST);
  18253. thread t = thread([&] { svr.listen_after_bind(); });
  18254. auto se = detail::scope_exit([&] {
  18255. svr.stop();
  18256. t.join();
  18257. });
  18258. svr.wait_until_ready();
  18259. std::string resp;
  18260. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18261. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18262. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18263. // Exactly one response: the route handler must not run after the 417.
  18264. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18265. }
  18266. #ifndef _WIN32
  18267. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18268. static constexpr char reject[] = "Unauthorized";
  18269. static constexpr char accept[] = "Upload accepted";
  18270. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18271. Server svr;
  18272. svr.set_expect_100_continue_handler(
  18273. [](const Request & /*req*/, Response &res) {
  18274. res.status = StatusCode::Unauthorized_401;
  18275. res.set_content(reject, "text/plain");
  18276. return res.status;
  18277. });
  18278. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18279. res.set_content(accept, "text/plain");
  18280. });
  18281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18282. auto se = detail::scope_exit([&] {
  18283. svr.stop();
  18284. thread.join();
  18285. ASSERT_FALSE(svr.is_running());
  18286. });
  18287. svr.wait_until_ready();
  18288. {
  18289. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18290. curl_easy_init(), &curl_easy_cleanup};
  18291. ASSERT_NE(curl, nullptr);
  18292. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18293. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18294. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18295. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18296. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18297. &curl_slist_free_all};
  18298. ASSERT_NE(list, nullptr);
  18299. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18300. struct read_data {
  18301. uint64_t read_size;
  18302. uint64_t total_size;
  18303. } data = {0, total_size};
  18304. using read_callback_t =
  18305. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18306. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18307. void *userdata) -> size_t {
  18308. read_data *d = (read_data *)userdata;
  18309. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18310. std::fill_n(ptr, size * nmemb, 'A');
  18311. d->read_size += size * nmemb;
  18312. return size * nmemb;
  18313. };
  18314. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18315. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18316. std::vector<char> buffer;
  18317. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18318. using write_callback_t =
  18319. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18320. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18321. void *userdata) -> size_t {
  18322. std::vector<char> *buf = (std::vector<char> *)userdata;
  18323. buf->reserve(buf->size() + size * nmemb + 1);
  18324. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18325. return size * nmemb;
  18326. };
  18327. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18328. {
  18329. const auto res = curl_easy_perform(curl.get());
  18330. ASSERT_EQ(res, CURLE_OK);
  18331. }
  18332. {
  18333. auto response_code = long{};
  18334. const auto res =
  18335. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18336. ASSERT_EQ(res, CURLE_OK);
  18337. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18338. }
  18339. {
  18340. auto dl = curl_off_t{};
  18341. const auto res =
  18342. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18343. ASSERT_EQ(res, CURLE_OK);
  18344. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18345. }
  18346. {
  18347. buffer.push_back('\0');
  18348. ASSERT_STRCASEEQ(buffer.data(), reject);
  18349. }
  18350. }
  18351. }
  18352. #endif
  18353. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18354. // Regression test for #2458.
  18355. //
  18356. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18357. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18358. // ticket can make the client socket spuriously readable during the
  18359. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18360. // the client withholds the body and then blocks reading a response that never
  18361. // comes, failing with `Failed to read connection`.
  18362. //
  18363. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18364. // within the timeout. This raw OpenSSL server deliberately never sends
  18365. // `100 Continue`; the client must still deliver the body and receive 200.
  18366. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18367. signal(SIGPIPE, SIG_IGN);
  18368. const auto port = PORT + 4;
  18369. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18370. ASSERT_NE(srv, INVALID_SOCKET);
  18371. int opt = 1;
  18372. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18373. sockaddr_in addr{};
  18374. addr.sin_family = AF_INET;
  18375. addr.sin_port = htons(static_cast<uint16_t>(port));
  18376. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18377. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18378. ASSERT_EQ(0, ::listen(srv, 1));
  18379. std::atomic<size_t> server_body_bytes{0};
  18380. auto server_thread = std::thread([&] {
  18381. sockaddr_in cli_addr{};
  18382. socklen_t cli_len = sizeof(cli_addr);
  18383. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18384. if (cli == INVALID_SOCKET) { return; }
  18385. // Bound the lifetime of the server side so a buggy client (which never
  18386. // sends the body) cannot make this thread block forever on join.
  18387. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18388. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18389. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18390. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18391. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18392. SSL *ssl = SSL_new(ctx);
  18393. SSL_set_fd(ssl, static_cast<int>(cli));
  18394. if (SSL_accept(ssl) > 0) {
  18395. // Read the request headers. Reading here also flushes the TLS 1.3
  18396. // session tickets to the client. Deliberately do NOT send
  18397. // `100 Continue`.
  18398. std::string buf;
  18399. char tmp[1024];
  18400. while (buf.find("\r\n\r\n") == std::string::npos) {
  18401. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18402. if (n <= 0) { break; }
  18403. buf.append(tmp, static_cast<size_t>(n));
  18404. }
  18405. // A correct client sends the body now; count what arrives.
  18406. auto pos = buf.find("\r\n\r\n");
  18407. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18408. while (body < 4096) {
  18409. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18410. if (n <= 0) { break; }
  18411. body += static_cast<size_t>(n);
  18412. }
  18413. server_body_bytes = body;
  18414. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18415. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18416. SSL_shutdown(ssl);
  18417. }
  18418. SSL_free(ssl);
  18419. detail::close_socket(cli);
  18420. SSL_CTX_free(ctx);
  18421. });
  18422. auto se = detail::scope_exit([&] {
  18423. server_thread.join();
  18424. detail::close_socket(srv);
  18425. });
  18426. SSLClient cli("127.0.0.1", port);
  18427. cli.enable_server_certificate_verification(false);
  18428. cli.set_connection_timeout(5, 0);
  18429. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18430. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18431. std::string body(4096, 'A');
  18432. auto res = cli.Put("/api/test", body, "application/json");
  18433. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18434. EXPECT_EQ(StatusCode::OK_200, res->status);
  18435. EXPECT_EQ(body.size(), server_body_bytes.load());
  18436. }
  18437. #endif
  18438. template <typename S, typename C>
  18439. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18440. svr.Get("/stream", [&](const Request &, Response &res) {
  18441. auto data = new std::string("01234567890123456789");
  18442. res.set_content_provider(
  18443. data->size(), "text/plain",
  18444. [&, data](size_t offset, size_t length, DataSink &sink) {
  18445. const size_t DATA_CHUNK_SIZE = 4;
  18446. const auto &d = *data;
  18447. std::this_thread::sleep_for(std::chrono::seconds(1));
  18448. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18449. return true;
  18450. },
  18451. [data](bool success) {
  18452. EXPECT_FALSE(success);
  18453. delete data;
  18454. });
  18455. });
  18456. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18457. auto i = new size_t(0);
  18458. res.set_content_provider(
  18459. "text/plain",
  18460. [i](size_t, DataSink &sink) {
  18461. if (*i < 5) {
  18462. std::this_thread::sleep_for(std::chrono::seconds(1));
  18463. sink.write("abcd", 4);
  18464. (*i)++;
  18465. } else {
  18466. sink.done();
  18467. }
  18468. return true;
  18469. },
  18470. [i](bool success) {
  18471. EXPECT_FALSE(success);
  18472. delete i;
  18473. });
  18474. });
  18475. svr.Get("/chunked", [&](const Request &, Response &res) {
  18476. auto i = new size_t(0);
  18477. res.set_chunked_content_provider(
  18478. "text/plain",
  18479. [i](size_t, DataSink &sink) {
  18480. if (*i < 5) {
  18481. std::this_thread::sleep_for(std::chrono::seconds(1));
  18482. sink.os << "abcd";
  18483. (*i)++;
  18484. } else {
  18485. sink.done();
  18486. }
  18487. return true;
  18488. },
  18489. [i](bool success) {
  18490. EXPECT_FALSE(success);
  18491. delete i;
  18492. });
  18493. });
  18494. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18495. auto se = detail::scope_exit([&] {
  18496. svr.stop();
  18497. listen_thread.join();
  18498. ASSERT_FALSE(svr.is_running());
  18499. });
  18500. svr.wait_until_ready();
  18501. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18502. {
  18503. auto start = std::chrono::steady_clock::now();
  18504. auto res = cli.Get("/stream");
  18505. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18506. std::chrono::steady_clock::now() - start)
  18507. .count();
  18508. ASSERT_FALSE(res);
  18509. EXPECT_EQ(Error::Read, res.error());
  18510. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18511. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18512. }
  18513. {
  18514. auto start = std::chrono::steady_clock::now();
  18515. auto res = cli.Get("/stream_without_length");
  18516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18517. std::chrono::steady_clock::now() - start)
  18518. .count();
  18519. ASSERT_FALSE(res);
  18520. EXPECT_EQ(Error::Read, res.error());
  18521. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18522. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18523. }
  18524. {
  18525. auto start = std::chrono::steady_clock::now();
  18526. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18527. EXPECT_EQ("abcd", string(data, data_length));
  18528. return true;
  18529. });
  18530. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18531. std::chrono::steady_clock::now() - start)
  18532. .count();
  18533. ASSERT_FALSE(res);
  18534. EXPECT_EQ(Error::Read, res.error());
  18535. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18536. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18537. }
  18538. }
  18539. TEST(MaxTimeoutTest, ContentStream) {
  18540. time_t timeout = 2000;
  18541. time_t threshold = 200;
  18542. Server svr;
  18543. Client cli("localhost", PORT);
  18544. max_timeout_test(svr, cli, timeout, threshold);
  18545. }
  18546. #ifdef CPPHTTPLIB_SSL_ENABLED
  18547. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18548. time_t timeout = 2000;
  18549. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18551. SSLClient cli("localhost", PORT);
  18552. cli.enable_server_certificate_verification(false);
  18553. max_timeout_test(svr, cli, timeout, threshold);
  18554. }
  18555. #endif
  18556. class EventDispatcher {
  18557. public:
  18558. EventDispatcher() {}
  18559. bool wait_event(DataSink *sink) {
  18560. unique_lock<mutex> lk(m_);
  18561. int id = id_;
  18562. // Wait with timeout to prevent hanging if client disconnects
  18563. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18564. [&] { return cid_ == id; })) {
  18565. return false; // Timeout occurred
  18566. }
  18567. sink->write(message_.data(), message_.size());
  18568. return true;
  18569. }
  18570. void send_event(const string &message) {
  18571. lock_guard<mutex> lk(m_);
  18572. cid_ = id_++;
  18573. message_ = message;
  18574. cv_.notify_all();
  18575. }
  18576. private:
  18577. mutex m_;
  18578. condition_variable cv_;
  18579. atomic_int id_{0};
  18580. atomic_int cid_{-1};
  18581. string message_;
  18582. };
  18583. TEST(ClientInThreadTest, Issue2068) {
  18584. EventDispatcher ed;
  18585. Server svr;
  18586. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18587. res.set_chunked_content_provider("text/event-stream",
  18588. [&](size_t /*offset*/, DataSink &sink) {
  18589. return ed.wait_event(&sink);
  18590. });
  18591. });
  18592. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18593. svr.wait_until_ready();
  18594. thread event_thread([&] {
  18595. int id = 0;
  18596. while (svr.is_running()) {
  18597. this_thread::sleep_for(chrono::milliseconds(500));
  18598. std::stringstream ss;
  18599. ss << "data: " << id << "\n\n";
  18600. ed.send_event(ss.str());
  18601. id++;
  18602. }
  18603. });
  18604. auto se = detail::scope_exit([&] {
  18605. svr.stop();
  18606. listen_thread.join();
  18607. event_thread.join();
  18608. ASSERT_FALSE(svr.is_running());
  18609. });
  18610. {
  18611. auto client = detail::make_unique<Client>(HOST, PORT);
  18612. client->set_read_timeout(std::chrono::minutes(10));
  18613. std::atomic<bool> stop{false};
  18614. std::thread t([&] {
  18615. client->Get("/event1",
  18616. [&](const char *, size_t) -> bool { return !stop; });
  18617. });
  18618. std::this_thread::sleep_for(std::chrono::seconds(2));
  18619. stop = true;
  18620. client->stop();
  18621. t.join();
  18622. // Reset client after thread has finished
  18623. client.reset();
  18624. }
  18625. }
  18626. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18627. auto handled = false;
  18628. Server svr;
  18629. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. ASSERT_FALSE(handled);
  18636. });
  18637. svr.wait_until_ready();
  18638. // Two Content-Length headers with different values — must be rejected
  18639. auto req = "POST /test HTTP/1.1\r\n"
  18640. "Content-Length: 5\r\n"
  18641. "Content-Length: 10\r\n"
  18642. "\r\n"
  18643. "hello";
  18644. std::string response;
  18645. ASSERT_TRUE(send_request(1, req, &response));
  18646. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18647. response.substr(0, response.find("\r\n")));
  18648. }
  18649. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18650. auto handled = false;
  18651. Server svr;
  18652. svr.Post("/test", [&](const Request &, Response &res) {
  18653. handled = true;
  18654. res.set_content("ok", "text/plain");
  18655. });
  18656. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18657. auto se = detail::scope_exit([&] {
  18658. svr.stop();
  18659. t.join();
  18660. ASSERT_FALSE(svr.is_running());
  18661. ASSERT_TRUE(handled);
  18662. });
  18663. svr.wait_until_ready();
  18664. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18665. auto req = "POST /test HTTP/1.1\r\n"
  18666. "Host: localhost\r\n"
  18667. "Content-Length: 5\r\n"
  18668. "Content-Length: 5\r\n"
  18669. "\r\n"
  18670. "hello";
  18671. std::string response;
  18672. ASSERT_TRUE(send_request(1, req, &response));
  18673. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18674. }
  18675. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18676. Server svr;
  18677. svr.Get("/test", [](const Request &, Response &res) {
  18678. res.set_content("ok", "text/plain");
  18679. });
  18680. auto port = svr.bind_to_any_port(HOST);
  18681. thread t = thread([&] { svr.listen_after_bind(); });
  18682. auto se = detail::scope_exit([&] {
  18683. svr.stop();
  18684. t.join();
  18685. ASSERT_FALSE(svr.is_running());
  18686. });
  18687. svr.wait_until_ready();
  18688. auto status_line = [&](const std::string &host_lines) {
  18689. std::string res;
  18690. send_request(
  18691. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18692. &res, port);
  18693. return res.substr(0, res.find("\r\n"));
  18694. };
  18695. const char *accepted[] = {
  18696. "Host: localhost\r\n",
  18697. "Host: a.example:8080\r\n",
  18698. "Host: my_service\r\n",
  18699. "Host: [::1]:8080\r\n",
  18700. "Host: [fe80::1%25eth0]\r\n",
  18701. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18702. };
  18703. for (auto host_lines : accepted) {
  18704. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18705. }
  18706. const char *rejected[] = {
  18707. "Host: a.example\r\nHost: b.example\r\n",
  18708. "Host: a.example\r\nHost: a.example\r\n",
  18709. "Host: a@b.example\r\n",
  18710. "Host: a.example/b\r\n",
  18711. "Host: a.example\\b\r\n",
  18712. "Host: a.example?b\r\n",
  18713. "Host: a.example#b\r\n",
  18714. "Host: a.example b.example\r\n",
  18715. };
  18716. for (auto host_lines : rejected) {
  18717. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18718. << host_lines;
  18719. }
  18720. }
  18721. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18722. Server svr;
  18723. svr.Get("/", [](const Request &req, Response &res) {
  18724. EXPECT_EQ(2U, req.trailers.size());
  18725. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18726. // Denied
  18727. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18728. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18729. // Accepted
  18730. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18731. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18732. EXPECT_TRUE(req.has_trailer("X-World"));
  18733. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  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. const std::string req = "GET / HTTP/1.1\r\n"
  18744. "Transfer-Encoding: chunked\r\n"
  18745. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18746. "\r\n"
  18747. "0\r\n"
  18748. "Content-Length: 10\r\n"
  18749. "Host: internal.local\r\n"
  18750. "Content-Type: malicious/content\r\n"
  18751. "Cookie: any\r\n"
  18752. "Set-Cookie: any\r\n"
  18753. "X-Forwarded-For: attacker.com\r\n"
  18754. "X-Real-Ip: 1.1.1.1\r\n"
  18755. "X-Hello: hello\r\n"
  18756. "X-World: world\r\n"
  18757. "\r\n";
  18758. std::string res;
  18759. ASSERT_TRUE(send_request(1, req, &res));
  18760. }
  18761. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18762. // several field lines, and the combined value is what has to be parsed. A
  18763. // Trailer field split across lines therefore declares every name it lists;
  18764. // reading only the first line silently drops the trailers the later lines
  18765. // declare. The prohibited-trailer filter still applies to every line.
  18766. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18767. Server svr;
  18768. size_t observed_trailer_count = 0;
  18769. std::string observed_hello;
  18770. std::string observed_world;
  18771. bool observed_content_length = true;
  18772. svr.Get("/", [&](const Request &req, Response &res) {
  18773. observed_trailer_count = req.trailers.size();
  18774. observed_hello = req.get_trailer_value("X-Hello");
  18775. observed_world = req.get_trailer_value("X-World");
  18776. observed_content_length = req.has_trailer("Content-Length");
  18777. res.set_content("ok", "text/plain");
  18778. });
  18779. auto port = svr.bind_to_any_port(HOST);
  18780. thread t = thread([&]() { svr.listen_after_bind(); });
  18781. auto se = detail::scope_exit([&] {
  18782. svr.stop();
  18783. t.join();
  18784. ASSERT_FALSE(svr.is_running());
  18785. });
  18786. svr.wait_until_ready();
  18787. const std::string req = "GET / HTTP/1.1\r\n"
  18788. "Host: localhost\r\n"
  18789. "Transfer-Encoding: chunked\r\n"
  18790. "Trailer: X-Hello\r\n"
  18791. "Trailer: X-World, Content-Length\r\n"
  18792. "\r\n"
  18793. "0\r\n"
  18794. "X-Hello: hello\r\n"
  18795. "X-World: world\r\n"
  18796. "Content-Length: 10\r\n"
  18797. "\r\n";
  18798. std::string res;
  18799. ASSERT_TRUE(send_request(1, req, &res, port));
  18800. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18801. // Accepted: both field lines contribute to the declared set
  18802. EXPECT_EQ(2U, observed_trailer_count);
  18803. EXPECT_EQ(observed_hello, "hello");
  18804. EXPECT_EQ(observed_world, "world");
  18805. // Denied: a prohibited name stays prohibited on a later field line
  18806. EXPECT_FALSE(observed_content_length);
  18807. }
  18808. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18809. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18810. // unbounded run of fields that are never declared, because the counter would
  18811. // only advance for declared fields.
  18812. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18813. Server svr;
  18814. bool handler_called = false;
  18815. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18816. handler_called = true;
  18817. res.set_content("ok", "text/plain");
  18818. });
  18819. auto port = svr.bind_to_any_port(HOST);
  18820. thread t = thread([&]() { svr.listen_after_bind(); });
  18821. auto se = detail::scope_exit([&] {
  18822. svr.stop();
  18823. t.join();
  18824. ASSERT_FALSE(svr.is_running());
  18825. });
  18826. svr.wait_until_ready();
  18827. // Declare nothing, then send far more undeclared trailer fields than the
  18828. // header-count limit. Parsing must stop and reject the request rather than
  18829. // read every line.
  18830. std::string req = "GET / HTTP/1.1\r\n"
  18831. "Transfer-Encoding: chunked\r\n"
  18832. "\r\n"
  18833. "0\r\n";
  18834. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18835. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18836. }
  18837. req += "\r\n";
  18838. std::string res;
  18839. ASSERT_TRUE(send_request(1, req, &res, port));
  18840. // The request is rejected before the handler runs.
  18841. EXPECT_FALSE(handler_called);
  18842. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18843. }
  18844. // The set of declared trailer names is capped so a peer cannot grow it without
  18845. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18846. // declared past the cap is not honored, even if the field is actually sent.
  18847. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18848. Server svr;
  18849. // One name inside the cap and one past it, so the test tracks the cap rather
  18850. // than a fixed count.
  18851. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18852. const std::string within_cap_name = "X-T-0";
  18853. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18854. bool observed_within_cap = false;
  18855. bool observed_past_cap = false;
  18856. svr.Get("/", [&](const Request &req, Response &res) {
  18857. observed_within_cap = req.has_trailer(within_cap_name);
  18858. observed_past_cap = req.has_trailer(past_cap_name);
  18859. res.set_content("ok", "text/plain");
  18860. });
  18861. auto port = svr.bind_to_any_port(HOST);
  18862. thread t = thread([&]() { svr.listen_after_bind(); });
  18863. auto se = detail::scope_exit([&] {
  18864. svr.stop();
  18865. t.join();
  18866. ASSERT_FALSE(svr.is_running());
  18867. });
  18868. svr.wait_until_ready();
  18869. // Declare more trailer names than the cap in a single Trailer field, then
  18870. // actually send the first (within the cap) and the last (past it).
  18871. std::string trailer_decl = "Trailer: ";
  18872. for (int i = 0; i < declared_count; i++) {
  18873. if (i != 0) { trailer_decl += ", "; }
  18874. trailer_decl += "X-T-" + std::to_string(i);
  18875. }
  18876. trailer_decl += "\r\n";
  18877. const std::string req = "GET / HTTP/1.1\r\n"
  18878. "Host: localhost\r\n"
  18879. "Transfer-Encoding: chunked\r\n" +
  18880. trailer_decl +
  18881. "\r\n"
  18882. "0\r\n" +
  18883. within_cap_name + ": a\r\n" + past_cap_name +
  18884. ": b\r\n"
  18885. "\r\n";
  18886. std::string res;
  18887. ASSERT_TRUE(send_request(1, req, &res, port));
  18888. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18889. // A name within the cap is honored; one declared past the cap is dropped.
  18890. EXPECT_TRUE(observed_within_cap);
  18891. EXPECT_FALSE(observed_past_cap);
  18892. }
  18893. // A direct client that is not listed in trusted_proxies must not be able to
  18894. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18895. // the peer address on the actual TCP connection determines whether the
  18896. // header is honored.
  18897. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18898. Server svr;
  18899. // Deliberately does NOT include the loopback address the test client
  18900. // actually connects from, so the direct connection is not a trusted proxy.
  18901. svr.set_trusted_proxies({"203.0.113.66"});
  18902. std::string observed_remote_addr;
  18903. svr.Get("/ip", [&](const Request &req, Response &res) {
  18904. observed_remote_addr = req.remote_addr;
  18905. res.set_content("ok", "text/plain");
  18906. });
  18907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18908. auto se = detail::scope_exit([&] {
  18909. svr.stop();
  18910. t.join();
  18911. ASSERT_FALSE(svr.is_running());
  18912. });
  18913. svr.wait_until_ready();
  18914. Client cli(HOST, PORT);
  18915. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18917. EXPECT_EQ(StatusCode::OK_200, res->status);
  18918. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18919. // ignored entirely and the real connection-level address retained.
  18920. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18921. observed_remote_addr == "127.0.0.1");
  18922. }
  18923. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18924. Server svr;
  18925. std::string observed_remote_addr;
  18926. std::string observed_xff;
  18927. svr.Get("/ip", [&](const Request &req, Response &res) {
  18928. observed_remote_addr = req.remote_addr;
  18929. observed_xff = req.get_header_value("X-Forwarded-For");
  18930. res.set_content("ok", "text/plain");
  18931. });
  18932. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18933. auto se = detail::scope_exit([&] {
  18934. svr.stop();
  18935. t.join();
  18936. ASSERT_FALSE(svr.is_running());
  18937. });
  18938. svr.wait_until_ready();
  18939. Client cli(HOST, PORT);
  18940. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18942. EXPECT_EQ(StatusCode::OK_200, res->status);
  18943. EXPECT_EQ(observed_xff, "203.0.113.66");
  18944. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18945. observed_remote_addr == "127.0.0.1");
  18946. }
  18947. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18948. Server svr;
  18949. svr.set_trusted_proxies({"203.0.113.66"});
  18950. std::string observed_remote_addr;
  18951. std::string observed_xff;
  18952. svr.Get("/ip", [&](const Request &req, Response &res) {
  18953. observed_remote_addr = req.remote_addr;
  18954. observed_xff = req.get_header_value("X-Forwarded-For");
  18955. res.set_content("ok", "text/plain");
  18956. });
  18957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18958. auto se = detail::scope_exit([&] {
  18959. svr.stop();
  18960. t.join();
  18961. ASSERT_FALSE(svr.is_running());
  18962. });
  18963. svr.wait_until_ready();
  18964. Client cli(HOST, PORT);
  18965. auto res = cli.Get("/ip");
  18966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18967. EXPECT_EQ(StatusCode::OK_200, res->status);
  18968. EXPECT_EQ(observed_xff, "");
  18969. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18970. observed_remote_addr == "127.0.0.1");
  18971. }
  18972. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18973. Server svr;
  18974. // Include the loopback address the test client actually connects from, so
  18975. // the direct connection itself is recognized as the trusted proxy hop.
  18976. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18977. std::string observed_remote_addr;
  18978. std::string observed_xff;
  18979. svr.Get("/ip", [&](const Request &req, Response &res) {
  18980. observed_remote_addr = req.remote_addr;
  18981. observed_xff = req.get_header_value("X-Forwarded-For");
  18982. res.set_content("ok", "text/plain");
  18983. });
  18984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18985. auto se = detail::scope_exit([&] {
  18986. svr.stop();
  18987. t.join();
  18988. ASSERT_FALSE(svr.is_running());
  18989. });
  18990. svr.wait_until_ready();
  18991. Client cli(HOST, PORT);
  18992. auto res = cli.Get(
  18993. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18995. EXPECT_EQ(StatusCode::OK_200, res->status);
  18996. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18997. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18998. }
  18999. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19000. Server svr;
  19001. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19002. std::string observed_remote_addr;
  19003. std::string observed_xff;
  19004. svr.Get("/ip", [&](const Request &req, Response &res) {
  19005. observed_remote_addr = req.remote_addr;
  19006. observed_xff = req.get_header_value("X-Forwarded-For");
  19007. res.set_content("ok", "text/plain");
  19008. });
  19009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19010. auto se = detail::scope_exit([&] {
  19011. svr.stop();
  19012. t.join();
  19013. ASSERT_FALSE(svr.is_running());
  19014. });
  19015. svr.wait_until_ready();
  19016. Client cli(HOST, PORT);
  19017. auto res = cli.Get(
  19018. "/ip",
  19019. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19021. EXPECT_EQ(StatusCode::OK_200, res->status);
  19022. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19023. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19024. }
  19025. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19026. Server svr;
  19027. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19028. std::string observed_remote_addr;
  19029. std::string observed_xff;
  19030. svr.Get("/ip", [&](const Request &req, Response &res) {
  19031. observed_remote_addr = req.remote_addr;
  19032. observed_xff = req.get_header_value("X-Forwarded-For");
  19033. res.set_content("ok", "text/plain");
  19034. });
  19035. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19036. auto se = detail::scope_exit([&] {
  19037. svr.stop();
  19038. t.join();
  19039. ASSERT_FALSE(svr.is_running());
  19040. });
  19041. svr.wait_until_ready();
  19042. Client cli(HOST, PORT);
  19043. auto res = cli.Get(
  19044. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19046. EXPECT_EQ(StatusCode::OK_200, res->status);
  19047. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19048. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19049. // and must not be selected.
  19050. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19051. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19052. }
  19053. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19054. Server svr;
  19055. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19056. std::string observed_remote_addr;
  19057. svr.Get("/ip", [&](const Request &req, Response &res) {
  19058. observed_remote_addr = req.remote_addr;
  19059. res.set_content("ok", "text/plain");
  19060. });
  19061. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19062. auto se = detail::scope_exit([&] {
  19063. svr.stop();
  19064. t.join();
  19065. ASSERT_FALSE(svr.is_running());
  19066. });
  19067. svr.wait_until_ready();
  19068. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19069. // a forged address and the trusted proxy's own address; the forged value must
  19070. // not win over the address the trusted proxy actually recorded.
  19071. Client cli(HOST, PORT);
  19072. auto res = cli.Get(
  19073. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19075. EXPECT_EQ(StatusCode::OK_200, res->status);
  19076. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19077. }
  19078. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19079. Server svr;
  19080. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19081. std::string observed_remote_addr;
  19082. std::string observed_xff;
  19083. svr.Get("/ip", [&](const Request &req, Response &res) {
  19084. observed_remote_addr = req.remote_addr;
  19085. observed_xff = req.get_header_value("X-Forwarded-For");
  19086. res.set_content("ok", "text/plain");
  19087. });
  19088. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19089. auto se = detail::scope_exit([&] {
  19090. svr.stop();
  19091. t.join();
  19092. ASSERT_FALSE(svr.is_running());
  19093. });
  19094. svr.wait_until_ready();
  19095. Client cli(HOST, PORT);
  19096. auto res = cli.Get(
  19097. "/ip",
  19098. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19100. EXPECT_EQ(StatusCode::OK_200, res->status);
  19101. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19102. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19103. }
  19104. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19105. Server svr;
  19106. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19107. std::string observed_remote_addr;
  19108. std::string observed_xff;
  19109. svr.Get("/ip", [&](const Request &req, Response &res) {
  19110. observed_remote_addr = req.remote_addr;
  19111. observed_xff = req.get_header_value("X-Forwarded-For");
  19112. res.set_content("ok", "text/plain");
  19113. });
  19114. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19115. auto se = detail::scope_exit([&] {
  19116. svr.stop();
  19117. t.join();
  19118. ASSERT_FALSE(svr.is_running());
  19119. });
  19120. svr.wait_until_ready();
  19121. std::string raw_req =
  19122. "GET /ip HTTP/1.1\r\n"
  19123. "Host: localhost\r\n"
  19124. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19125. "Connection: close\r\n"
  19126. "\r\n";
  19127. std::string out;
  19128. ASSERT_TRUE(send_request(5, raw_req, &out));
  19129. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19130. // Header parser trims surrounding whitespace of the header value
  19131. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19132. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19133. }
  19134. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19135. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19136. // their own X-Forwarded-For as a separate field line rather than extending the
  19137. // one the client sent, so every occurrence has to be taken into account.
  19138. // Reading only the first one hands back the address the client chose.
  19139. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19140. Server svr;
  19141. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19142. std::string observed_remote_addr;
  19143. size_t observed_xff_count = 0;
  19144. svr.Get("/ip", [&](const Request &req, Response &res) {
  19145. observed_remote_addr = req.remote_addr;
  19146. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19147. res.set_content("ok", "text/plain");
  19148. });
  19149. auto port = svr.bind_to_any_port(HOST);
  19150. thread t = thread([&]() { svr.listen_after_bind(); });
  19151. auto se = detail::scope_exit([&] {
  19152. svr.stop();
  19153. t.join();
  19154. ASSERT_FALSE(svr.is_running());
  19155. });
  19156. svr.wait_until_ready();
  19157. // The client supplies the first field line; the trusted proxy appends the
  19158. // address it observed as a second one.
  19159. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19160. "Host: localhost\r\n"
  19161. "X-Forwarded-For: 1.2.3.4\r\n"
  19162. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19163. "Connection: close\r\n"
  19164. "\r\n";
  19165. std::string out;
  19166. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19167. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19168. EXPECT_EQ(observed_xff_count, 2U);
  19169. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19170. // The same chain spread over one field line per hop derives the same client
  19171. // address, i.e. the split and the comma-joined representations agree.
  19172. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19173. "Host: localhost\r\n"
  19174. "X-Forwarded-For: 1.2.3.4\r\n"
  19175. "X-Forwarded-For: 198.51.100.23\r\n"
  19176. "X-Forwarded-For: 192.0.2.45\r\n"
  19177. "Connection: close\r\n"
  19178. "\r\n";
  19179. out.clear();
  19180. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19181. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19182. EXPECT_EQ(observed_xff_count, 3U);
  19183. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19184. }
  19185. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19186. // crash the server (it used to call front() on an empty vector inside
  19187. // get_client_ip). The connection-level remote address must be retained instead.
  19188. static void run_malformed_xff_test(const std::string &xff_value) {
  19189. Server svr;
  19190. svr.set_trusted_proxies({"192.0.2.45"});
  19191. std::string observed_remote_addr;
  19192. svr.Get("/ip", [&](const Request &req, Response &res) {
  19193. observed_remote_addr = req.remote_addr;
  19194. res.set_content("ok", "text/plain");
  19195. });
  19196. int port = 0;
  19197. thread t = thread([&]() {
  19198. port = svr.bind_to_any_port(HOST);
  19199. svr.listen_after_bind();
  19200. });
  19201. auto se = detail::scope_exit([&] {
  19202. svr.stop();
  19203. t.join();
  19204. ASSERT_FALSE(svr.is_running());
  19205. });
  19206. svr.wait_until_ready();
  19207. Client cli(HOST, port);
  19208. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19210. EXPECT_EQ(StatusCode::OK_200, res->status);
  19211. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19212. observed_remote_addr == "127.0.0.1");
  19213. }
  19214. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19215. run_malformed_xff_test("");
  19216. }
  19217. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19218. run_malformed_xff_test(",");
  19219. }
  19220. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19221. run_malformed_xff_test(", , ,");
  19222. }
  19223. // The same rule applies to Accept: a request whose acceptable types are spread
  19224. // over several field lines must be negotiated against all of them.
  19225. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19226. // case-insensitive connection options. Comparing the whole field value against
  19227. // one option misses a client that sends several of them, and misses every
  19228. // casing but the one written in the comparison.
  19229. //
  19230. // Sends req, reads the response, then reuses the same socket for a second
  19231. // request to find out whether the server kept the connection.
  19232. static void probe_connection_reuse(int port, const std::string &req,
  19233. bool *announced_close, bool *reusable) {
  19234. auto error = Error::Success;
  19235. auto sock = detail::create_client_socket(
  19236. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19237. /*connection_timeout_sec=*/5, 0,
  19238. /*read_timeout_sec=*/1, 0,
  19239. /*write_timeout_sec=*/5, 0, std::string(), error);
  19240. ASSERT_NE(sock, INVALID_SOCKET);
  19241. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19242. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19243. "Host: localhost\r\n"
  19244. "Connection: close\r\n"
  19245. "\r\n";
  19246. std::string first_response;
  19247. std::string second_response;
  19248. detail::process_client_socket(
  19249. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19250. [&](Stream &strm) {
  19251. if (strm.write(req.data(), req.size()) !=
  19252. static_cast<ssize_t>(req.size())) {
  19253. return false;
  19254. }
  19255. char buf[512];
  19256. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19257. // Headers plus the two-byte body of the handler below
  19258. while (reader.getline()) {
  19259. first_response += reader.ptr();
  19260. if (first_response.find("ok") != std::string::npos) { break; }
  19261. }
  19262. if (strm.write(second.data(), second.size()) !=
  19263. static_cast<ssize_t>(second.size())) {
  19264. return true;
  19265. }
  19266. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19267. while (reader2.getline()) {
  19268. second_response += reader2.ptr();
  19269. if (second_response.find("ok") != std::string::npos) { break; }
  19270. }
  19271. return true;
  19272. });
  19273. *announced_close =
  19274. first_response.find("Connection: close") != std::string::npos;
  19275. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19276. }
  19277. class ConnectionTokenTest : public ::testing::Test {
  19278. protected:
  19279. void SetUp() override {
  19280. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19281. res.set_content("ok", "text/plain");
  19282. });
  19283. port_ = svr_.bind_to_any_port(HOST);
  19284. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19285. svr_.wait_until_ready();
  19286. }
  19287. void TearDown() override {
  19288. svr_.stop();
  19289. if (thread_.joinable()) { thread_.join(); }
  19290. }
  19291. Server svr_;
  19292. int port_ = 0;
  19293. thread thread_;
  19294. };
  19295. // "close" alongside another option still closes the connection, and the
  19296. // response says so rather than leaving the peer to discover it.
  19297. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19298. bool announced_close = false;
  19299. bool reusable = true;
  19300. probe_connection_reuse(port_,
  19301. "GET /keepalive HTTP/1.1\r\n"
  19302. "Host: localhost\r\n"
  19303. "Connection: keep-alive, close\r\n"
  19304. "\r\n",
  19305. &announced_close, &reusable);
  19306. EXPECT_TRUE(announced_close);
  19307. EXPECT_FALSE(reusable);
  19308. }
  19309. // "close" split over two field lines is the same list, so it is honored too.
  19310. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19311. bool announced_close = false;
  19312. bool reusable = true;
  19313. probe_connection_reuse(port_,
  19314. "GET /keepalive HTTP/1.1\r\n"
  19315. "Host: localhost\r\n"
  19316. "Connection: keep-alive\r\n"
  19317. "Connection: close\r\n"
  19318. "\r\n",
  19319. &announced_close, &reusable);
  19320. EXPECT_TRUE(announced_close);
  19321. EXPECT_FALSE(reusable);
  19322. }
  19323. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19324. // keep-alive in the spelling everyone actually sends keeps its connection.
  19325. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19326. bool announced_close = false;
  19327. bool reusable = false;
  19328. probe_connection_reuse(port_,
  19329. "GET /keepalive HTTP/1.0\r\n"
  19330. "Host: localhost\r\n"
  19331. "Connection: keep-alive\r\n"
  19332. "\r\n",
  19333. &announced_close, &reusable);
  19334. EXPECT_FALSE(announced_close);
  19335. EXPECT_TRUE(reusable);
  19336. }
  19337. // A token the value merely contains is not the token itself.
  19338. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19339. bool announced_close = false;
  19340. bool reusable = false;
  19341. probe_connection_reuse(port_,
  19342. "GET /keepalive HTTP/1.1\r\n"
  19343. "Host: localhost\r\n"
  19344. "Connection: notclose\r\n"
  19345. "\r\n",
  19346. &announced_close, &reusable);
  19347. EXPECT_FALSE(announced_close);
  19348. EXPECT_TRUE(reusable);
  19349. }
  19350. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19351. Server svr;
  19352. std::vector<std::string> observed_types;
  19353. svr.Get("/", [&](const Request &req, Response &res) {
  19354. observed_types = req.accept_content_types;
  19355. res.set_content("ok", "text/plain");
  19356. });
  19357. auto port = svr.bind_to_any_port(HOST);
  19358. thread t = thread([&]() { svr.listen_after_bind(); });
  19359. auto se = detail::scope_exit([&] {
  19360. svr.stop();
  19361. t.join();
  19362. ASSERT_FALSE(svr.is_running());
  19363. });
  19364. svr.wait_until_ready();
  19365. Client cli(HOST, port);
  19366. Headers headers;
  19367. headers.emplace("Accept", "text/plain;q=0.5");
  19368. headers.emplace("Accept", "application/json");
  19369. auto res = cli.Get("/", headers);
  19370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19371. EXPECT_EQ(StatusCode::OK_200, res->status);
  19372. // Sorted by q-value, so the second field line's type comes first
  19373. ASSERT_EQ(2U, observed_types.size());
  19374. EXPECT_EQ("application/json", observed_types[0]);
  19375. EXPECT_EQ("text/plain", observed_types[1]);
  19376. }
  19377. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19378. // empty field line must not contribute a bare comma to the combined value.
  19379. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19380. Server svr;
  19381. std::vector<std::string> observed_types;
  19382. svr.Get("/", [&](const Request &req, Response &res) {
  19383. observed_types = req.accept_content_types;
  19384. res.set_content("ok", "text/plain");
  19385. });
  19386. auto port = svr.bind_to_any_port(HOST);
  19387. thread t = thread([&]() { svr.listen_after_bind(); });
  19388. auto se = detail::scope_exit([&] {
  19389. svr.stop();
  19390. t.join();
  19391. ASSERT_FALSE(svr.is_running());
  19392. });
  19393. svr.wait_until_ready();
  19394. // Empty first field line, then a real one
  19395. std::string raw_req = "GET / HTTP/1.1\r\n"
  19396. "Host: localhost\r\n"
  19397. "Accept:\r\n"
  19398. "Accept: application/json\r\n"
  19399. "Connection: close\r\n"
  19400. "\r\n";
  19401. std::string out;
  19402. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19403. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19404. ASSERT_EQ(1U, observed_types.size());
  19405. EXPECT_EQ("application/json", observed_types[0]);
  19406. }
  19407. // The skip in get_combined_header_value() is what keeps an empty field line
  19408. // from contributing a bare comma. Only a trailing empty field line exercises
  19409. // it: a leading one is already covered by the "combined is still empty" check,
  19410. // and parse_accept_header() now ignores the empty element either way, so the
  19411. // request-level test above can no longer tell the two apart.
  19412. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19413. Headers headers;
  19414. headers.emplace("Accept", "text/html");
  19415. headers.emplace("Accept", "");
  19416. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19417. headers.clear();
  19418. headers.emplace("Accept", "");
  19419. headers.emplace("Accept", "application/json");
  19420. EXPECT_EQ("application/json",
  19421. detail::get_combined_header_value(headers, "Accept"));
  19422. }
  19423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19424. // An encoding offered on a later Accept-Encoding field line is still offered.
  19425. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19426. Server svr;
  19427. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19428. res.set_content(std::string(1024, 'x'), "text/plain");
  19429. });
  19430. auto port = svr.bind_to_any_port(HOST);
  19431. thread t = thread([&]() { svr.listen_after_bind(); });
  19432. auto se = detail::scope_exit([&] {
  19433. svr.stop();
  19434. t.join();
  19435. ASSERT_FALSE(svr.is_running());
  19436. });
  19437. svr.wait_until_ready();
  19438. Client cli(HOST, port);
  19439. cli.set_decompress(false);
  19440. Headers headers;
  19441. headers.emplace("Accept-Encoding", "identity");
  19442. headers.emplace("Accept-Encoding", "gzip");
  19443. auto res = cli.Get("/", headers);
  19444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19445. EXPECT_EQ(StatusCode::OK_200, res->status);
  19446. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19447. }
  19448. #endif
  19449. #ifndef _WIN32
  19450. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19451. Server svr;
  19452. svr.Post("/post", [&](const Request &req, Response &res) {
  19453. res.set_content(req.body, "text/plain");
  19454. });
  19455. svr.Put("/put", [&](const Request &req, Response &res) {
  19456. res.set_content(req.body, "text/plain");
  19457. });
  19458. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19459. res.set_content(req.body, "text/plain");
  19460. });
  19461. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19462. res.set_content(req.body, "text/plain");
  19463. });
  19464. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19465. auto se = detail::scope_exit([&] {
  19466. svr.stop();
  19467. t.join();
  19468. ASSERT_FALSE(svr.is_running());
  19469. });
  19470. svr.wait_until_ready();
  19471. std::string resp;
  19472. // POST without Content-Length
  19473. ASSERT_TRUE(send_request(5,
  19474. "POST /post HTTP/1.1\r\n"
  19475. "Host: localhost\r\n"
  19476. "Connection: close\r\n"
  19477. "\r\n",
  19478. &resp));
  19479. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19480. // PUT without Content-Length
  19481. resp.clear();
  19482. ASSERT_TRUE(send_request(5,
  19483. "PUT /put HTTP/1.1\r\n"
  19484. "Host: localhost\r\n"
  19485. "Connection: close\r\n"
  19486. "\r\n",
  19487. &resp));
  19488. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19489. // PATCH without Content-Length
  19490. resp.clear();
  19491. ASSERT_TRUE(send_request(5,
  19492. "PATCH /patch HTTP/1.1\r\n"
  19493. "Host: localhost\r\n"
  19494. "Connection: close\r\n"
  19495. "\r\n",
  19496. &resp));
  19497. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19498. // DELETE without Content-Length
  19499. resp.clear();
  19500. ASSERT_TRUE(send_request(5,
  19501. "DELETE /delete HTTP/1.1\r\n"
  19502. "Host: localhost\r\n"
  19503. "Connection: close\r\n"
  19504. "\r\n",
  19505. &resp));
  19506. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19507. }
  19508. #endif
  19509. //==============================================================================
  19510. // open_stream() Tests
  19511. //==============================================================================
  19512. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19513. std::string result;
  19514. char buf[8192];
  19515. ssize_t n;
  19516. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19517. result.append(buf, static_cast<size_t>(n));
  19518. }
  19519. return result;
  19520. }
  19521. // Mock stream for unit tests
  19522. class MockStream : public Stream {
  19523. public:
  19524. std::string data;
  19525. size_t pos = 0;
  19526. ssize_t error_after = -1; // -1 = no error
  19527. explicit MockStream(const std::string &d, ssize_t err = -1)
  19528. : data(d), error_after(err) {}
  19529. bool is_readable() const override { return true; }
  19530. bool wait_readable() const override { return true; }
  19531. bool wait_writable() const override { return true; }
  19532. ssize_t read(char *ptr, size_t size) override {
  19533. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19534. if (pos >= data.size()) return 0;
  19535. size_t limit =
  19536. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19537. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19538. std::memcpy(ptr, data.data() + pos, to_read);
  19539. pos += to_read;
  19540. return static_cast<ssize_t>(to_read);
  19541. }
  19542. ssize_t write(const char *, size_t) override { return -1; }
  19543. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19544. ip = "127.0.0.1";
  19545. port = 0;
  19546. }
  19547. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19548. ip = "127.0.0.1";
  19549. port = 0;
  19550. }
  19551. socket_t socket() const override { return INVALID_SOCKET; }
  19552. time_t duration() const override { return 0; }
  19553. };
  19554. TEST(StreamHandleTest, Basic) {
  19555. ClientImpl::StreamHandle handle;
  19556. EXPECT_FALSE(handle.is_valid());
  19557. handle.response = detail::make_unique<Response>();
  19558. handle.error = Error::Connection;
  19559. EXPECT_FALSE(handle.is_valid());
  19560. handle.error = Error::Success;
  19561. EXPECT_TRUE(handle.is_valid());
  19562. }
  19563. TEST(BodyReaderTest, Basic) {
  19564. MockStream stream("Hello, World!");
  19565. detail::BodyReader reader;
  19566. reader.stream = &stream;
  19567. reader.content_length = 13;
  19568. char buf[32];
  19569. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19570. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19571. EXPECT_TRUE(reader.eof);
  19572. }
  19573. TEST(BodyReaderTest, NoStream) {
  19574. detail::BodyReader reader;
  19575. char buf[32];
  19576. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19577. EXPECT_EQ(Error::Connection, reader.last_error);
  19578. }
  19579. TEST(BodyReaderTest, Error) {
  19580. MockStream stream("Hello, World!", 5);
  19581. detail::BodyReader reader;
  19582. reader.stream = &stream;
  19583. reader.content_length = 13;
  19584. char buf[32];
  19585. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19586. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19587. EXPECT_EQ(Error::Read, reader.last_error);
  19588. }
  19589. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19590. // Mock-based StreamHandle tests relying on private internals are removed.
  19591. class OpenStreamTest : public ::testing::Test {
  19592. protected:
  19593. void SetUp() override {
  19594. svr_.Get("/hello", [](const Request &, Response &res) {
  19595. res.set_content("Hello World!", "text/plain");
  19596. });
  19597. svr_.Get("/large", [](const Request &, Response &res) {
  19598. res.set_content(std::string(10000, 'X'), "text/plain");
  19599. });
  19600. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19601. res.set_content("Hello World!", "image/jpeg");
  19602. res.set_header("Content-Encoding", "UTF-8");
  19603. });
  19604. svr_.Get("/chunked", [](const Request &, Response &res) {
  19605. res.set_chunked_content_provider("text/plain",
  19606. [](size_t offset, DataSink &sink) {
  19607. if (offset < 15) {
  19608. sink.write("chunk", 5);
  19609. return true;
  19610. }
  19611. sink.done();
  19612. return true;
  19613. });
  19614. });
  19615. svr_.Get("/compressible", [](const Request &, Response &res) {
  19616. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19617. DataSink &sink) {
  19618. if (offset < 100 * 1024) {
  19619. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19620. sink.write(chunk.data(), chunk.size());
  19621. return true;
  19622. }
  19623. sink.done();
  19624. return true;
  19625. });
  19626. });
  19627. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19628. [](const Request & /*req*/, Response &res) {
  19629. auto i = new int(0);
  19630. res.set_header("Trailer", "Content-Length, X-Allowed");
  19631. res.set_chunked_content_provider(
  19632. "text/plain",
  19633. [i](size_t /*offset*/, DataSink &sink) {
  19634. switch (*i) {
  19635. case 0: sink.os << "123"; break;
  19636. case 1: sink.os << "456"; break;
  19637. case 2: sink.os << "789"; break;
  19638. case 3: {
  19639. sink.done_with_trailer(
  19640. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19641. } break;
  19642. }
  19643. (*i)++;
  19644. return true;
  19645. },
  19646. [i](bool success) {
  19647. EXPECT_TRUE(success);
  19648. delete i;
  19649. });
  19650. });
  19651. // Echo headers endpoint for header-related tests
  19652. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19653. std::string body;
  19654. for (const auto &h : req.headers) {
  19655. body.append(h.first);
  19656. body.push_back(':');
  19657. body.append(h.second);
  19658. body.push_back('\n');
  19659. }
  19660. res.set_content(body, "text/plain");
  19661. });
  19662. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19663. std::string body;
  19664. for (const auto &h : req.headers) {
  19665. body.append(h.first);
  19666. body.push_back(':');
  19667. body.append(h.second);
  19668. body.push_back('\n');
  19669. }
  19670. res.set_content(body, "text/plain");
  19671. });
  19672. port_ = svr_.bind_to_any_port("127.0.0.1");
  19673. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19674. svr_.wait_until_ready();
  19675. }
  19676. void TearDown() override {
  19677. svr_.stop();
  19678. if (thread_.joinable()) thread_.join();
  19679. }
  19680. Server svr_;
  19681. std::thread thread_;
  19682. int port_ = 0;
  19683. };
  19684. TEST_F(OpenStreamTest, Basic) {
  19685. Client cli("127.0.0.1", port_);
  19686. auto handle = cli.open_stream("GET", "/hello");
  19687. EXPECT_TRUE(handle.is_valid());
  19688. EXPECT_EQ("Hello World!", read_all(handle));
  19689. }
  19690. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19691. Client cli("127.0.0.1", port_);
  19692. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19693. ASSERT_TRUE(handle.is_valid());
  19694. EXPECT_EQ("Hello World!", read_all(handle));
  19695. }
  19696. TEST_F(OpenStreamTest, SmallBuffer) {
  19697. Client cli("127.0.0.1", port_);
  19698. auto handle = cli.open_stream("GET", "/hello");
  19699. std::string result;
  19700. char buf[4];
  19701. ssize_t n;
  19702. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19703. result.append(buf, static_cast<size_t>(n));
  19704. EXPECT_EQ("Hello World!", result);
  19705. }
  19706. TEST_F(OpenStreamTest, DefaultHeaders) {
  19707. Client cli("127.0.0.1", port_);
  19708. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19709. {
  19710. auto handle = cli.open_stream("GET", "/echo-headers");
  19711. ASSERT_TRUE(handle.is_valid());
  19712. auto body = read_all(handle);
  19713. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19714. std::string::npos);
  19715. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19716. std::string::npos);
  19717. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19718. }
  19719. // open_stream POST with body and no explicit content_type should NOT add
  19720. // text/plain Content-Type (behavior differs from non-streaming path), but
  19721. // should include Content-Length
  19722. {
  19723. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19724. ASSERT_TRUE(handle.is_valid());
  19725. auto body = read_all(handle);
  19726. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19727. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19728. }
  19729. // open_stream POST with explicit Content-Type should preserve it
  19730. {
  19731. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19732. {{"Content-Type", "application/custom"}},
  19733. "{}", "application/custom");
  19734. ASSERT_TRUE(handle.is_valid());
  19735. auto body = read_all(handle);
  19736. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19737. }
  19738. // User-specified User-Agent must not be overwritten for stream API
  19739. {
  19740. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19741. {{"User-Agent", "MyAgent/1.2"}});
  19742. ASSERT_TRUE(handle.is_valid());
  19743. auto body = read_all(handle);
  19744. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19745. }
  19746. }
  19747. TEST_F(OpenStreamTest, Large) {
  19748. Client cli("127.0.0.1", port_);
  19749. auto handle = cli.open_stream("GET", "/large");
  19750. EXPECT_EQ(10000u, read_all(handle).size());
  19751. }
  19752. TEST_F(OpenStreamTest, ConnectionError) {
  19753. Client cli("127.0.0.1", 9999);
  19754. auto handle = cli.open_stream("GET", "/hello");
  19755. EXPECT_FALSE(handle.is_valid());
  19756. }
  19757. TEST_F(OpenStreamTest, Chunked) {
  19758. Client cli("127.0.0.1", port_);
  19759. auto handle = cli.open_stream("GET", "/chunked");
  19760. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19761. "Transfer-Encoding") == "chunked");
  19762. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19763. }
  19764. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19765. Client cli("127.0.0.1", port_);
  19766. auto handle =
  19767. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19768. ASSERT_TRUE(handle.is_valid());
  19769. // Consume body to allow trailers to be received/parsed
  19770. auto body = read_all(handle);
  19771. // Explicitly parse trailers (ensure trailers are available for assertion)
  19772. handle.parse_trailers_if_needed();
  19773. EXPECT_EQ(std::string("123456789"), body);
  19774. // The response should include a Trailer header declaring both names
  19775. ASSERT_TRUE(handle.response);
  19776. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19777. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19778. handle.response->get_header_value("Trailer"));
  19779. // Prohibited trailer must not be present
  19780. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19781. // Allowed trailer should be present
  19782. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19783. EXPECT_EQ(std::string("yes"),
  19784. handle.response->get_trailer_value("X-Allowed"));
  19785. // Verify trailers are NOT present as regular headers
  19786. EXPECT_EQ(std::string(""),
  19787. handle.response->get_header_value("Content-Length"));
  19788. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19789. }
  19790. // Accepts one connection on an OS-assigned port, which it hands over through
  19791. // port_promise, reads the request head and sends back response. after_send,
  19792. // if given, runs on the connection before it is closed.
  19793. static std::thread
  19794. serve_single_response(std::promise<int> &port_promise,
  19795. const std::string &response,
  19796. std::function<void(socket_t)> after_send = nullptr) {
  19797. return std::thread([&port_promise, response, after_send] {
  19798. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19799. default_socket_options(srv);
  19800. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19801. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19802. sockaddr_in addr{};
  19803. addr.sin_family = AF_INET;
  19804. addr.sin_port = htons(0); // Let OS assign a free port
  19805. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19806. int opt = 1;
  19807. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19808. #ifdef _WIN32
  19809. reinterpret_cast<const char *>(&opt),
  19810. #else
  19811. &opt,
  19812. #endif
  19813. sizeof(opt));
  19814. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19815. ::listen(srv, 1) != 0) {
  19816. port_promise.set_value(-1);
  19817. detail::close_socket(srv);
  19818. return;
  19819. }
  19820. socklen_t addr_len = sizeof(addr);
  19821. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19822. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19823. sockaddr_in cli_addr{};
  19824. socklen_t cli_len = sizeof(cli_addr);
  19825. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19826. if (cli != INVALID_SOCKET) {
  19827. // Read the complete HTTP request (until the blank line that terminates
  19828. // headers) before sending the response. If the server closes the socket
  19829. // while the client's request data is still unread in the kernel receive
  19830. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19831. // connection on both sides: it discards the client's receive buffer
  19832. // (which already holds our response) and causes any in-progress write on
  19833. // the client to fail with ECONNRESET. Reading all request data first
  19834. // ensures close() emits a graceful FIN.
  19835. {
  19836. char rbuf[256];
  19837. std::string req;
  19838. while (req.find("\r\n\r\n") == std::string::npos) {
  19839. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19840. if (n <= 0) { break; }
  19841. req.append(rbuf, static_cast<size_t>(n));
  19842. }
  19843. }
  19844. ::send(cli,
  19845. #ifdef _WIN32
  19846. static_cast<const char *>(response.c_str()),
  19847. static_cast<int>(response.size()),
  19848. #else
  19849. response.c_str(), response.size(),
  19850. #endif
  19851. 0);
  19852. if (after_send) { after_send(cli); }
  19853. detail::close_socket(cli);
  19854. }
  19855. detail::close_socket(srv);
  19856. });
  19857. }
  19858. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19859. #ifndef _WIN32
  19860. signal(SIGPIPE, SIG_IGN);
  19861. #endif
  19862. std::promise<int> port_promise;
  19863. auto port_future = port_promise.get_future();
  19864. auto server_thread =
  19865. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19866. "Content-Type: text/plain\r\n"
  19867. "Content-Length: not-a-number\r\n"
  19868. "Connection: close\r\n"
  19869. "\r\n"
  19870. "hello");
  19871. auto port = port_future.get();
  19872. ASSERT_GT(port, 0);
  19873. Client cli("127.0.0.1", port);
  19874. auto handle = cli.open_stream("GET", "/");
  19875. EXPECT_FALSE(handle.is_valid());
  19876. server_thread.join();
  19877. }
  19878. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19879. #ifndef _WIN32
  19880. signal(SIGPIPE, SIG_IGN);
  19881. #endif
  19882. std::promise<int> port_promise;
  19883. auto port_future = port_promise.get_future();
  19884. auto server_thread = serve_single_response(
  19885. port_promise, "HTTP/1.1 200 OK\r\n"
  19886. "Content-Type: text/plain\r\n"
  19887. "Content-Length: 99999999999999999999999999\r\n"
  19888. "Connection: close\r\n"
  19889. "\r\n"
  19890. "hello");
  19891. auto port = port_future.get();
  19892. ASSERT_GT(port, 0);
  19893. // Historically std::stoull would throw std::out_of_range here and crash
  19894. // the process, then parsing silently clamped to a bogus framing length and
  19895. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19896. // so the stream fails to open, matching the not-a-number case above. The
  19897. // process still must NOT terminate.
  19898. Client cli("127.0.0.1", port);
  19899. auto handle = cli.open_stream("GET", "/");
  19900. EXPECT_FALSE(handle.is_valid());
  19901. server_thread.join();
  19902. }
  19903. // Serves `response` to the single request `fn` makes with a fresh client.
  19904. template <typename Fn>
  19905. static void with_single_response(const std::string &response, Fn fn) {
  19906. #ifndef _WIN32
  19907. signal(SIGPIPE, SIG_IGN);
  19908. #endif
  19909. std::promise<int> port_promise;
  19910. auto port_future = port_promise.get_future();
  19911. auto server_thread = serve_single_response(port_promise, response);
  19912. auto se = detail::scope_exit([&] { server_thread.join(); });
  19913. auto port = port_future.get();
  19914. ASSERT_GT(port, 0);
  19915. Client cli("127.0.0.1", port);
  19916. fn(cli);
  19917. }
  19918. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19919. // Neither Content-Length nor chunked: the body ends at the close
  19920. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19921. "Connection: close\r\n"
  19922. "\r\n"
  19923. "hello";
  19924. with_single_response(close_delimited, [](Client &cli) {
  19925. auto handle = cli.open_stream("GET", "/");
  19926. ASSERT_TRUE(handle.is_valid());
  19927. EXPECT_EQ("hello", read_all(handle));
  19928. EXPECT_FALSE(handle.has_read_error());
  19929. });
  19930. // A close before the end of the Content-Length is still an error
  19931. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19932. "Content-Length: 10\r\n"
  19933. "\r\n"
  19934. "hello";
  19935. with_single_response(short_content_length, [](Client &cli) {
  19936. auto handle = cli.open_stream("GET", "/");
  19937. ASSERT_TRUE(handle.is_valid());
  19938. read_all(handle);
  19939. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19940. });
  19941. // So is a close before the last chunk
  19942. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19943. "Transfer-Encoding: chunked\r\n"
  19944. "\r\n"
  19945. "5\r\nhello\r\n";
  19946. with_single_response(short_chunked, [](Client &cli) {
  19947. auto handle = cli.open_stream("GET", "/");
  19948. ASSERT_TRUE(handle.is_valid());
  19949. read_all(handle);
  19950. EXPECT_TRUE(handle.has_read_error());
  19951. });
  19952. }
  19953. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19954. const char *responses[] = {
  19955. "HTTP/1.1 103 Early Hints\r\n"
  19956. "Link: </style.css>; rel=preload\r\n"
  19957. "\r\n"
  19958. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19959. "HTTP/1.1 100 Continue\r\n"
  19960. "X-Note: interim\r\n"
  19961. "\r\n"
  19962. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19963. };
  19964. for (auto response : responses) {
  19965. with_single_response(response, [](Client &cli) {
  19966. auto res = cli.Get("/");
  19967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19968. EXPECT_EQ(StatusCode::OK_200, res->status);
  19969. EXPECT_EQ("ok", res->body);
  19970. });
  19971. }
  19972. }
  19973. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19974. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19975. const std::string final_response =
  19976. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19977. std::string interims;
  19978. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19979. interims += interim;
  19980. }
  19981. with_single_response(interims + final_response, [](Client &cli) {
  19982. auto res = cli.Get("/");
  19983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19984. EXPECT_EQ("ok", res->body);
  19985. });
  19986. with_single_response(interims + interim + final_response, [](Client &cli) {
  19987. auto res = cli.Get("/");
  19988. ASSERT_FALSE(res);
  19989. EXPECT_EQ(Error::Read, res.error());
  19990. });
  19991. }
  19992. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19993. #ifndef _WIN32
  19994. signal(SIGPIPE, SIG_IGN);
  19995. #endif
  19996. // The server answers the head without asking for the body. Bytes it then
  19997. // reads on the connection would be taken for the body the request declared.
  19998. auto closed_by_client = false;
  19999. std::promise<int> port_promise;
  20000. auto server_thread = serve_single_response(
  20001. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20002. [&](socket_t sock) {
  20003. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20004. char buf[256];
  20005. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20006. });
  20007. Client cli("127.0.0.1", port_promise.get_future().get());
  20008. cli.set_keep_alive(true);
  20009. cli.set_read_timeout(1, 0);
  20010. // Long enough for the client to send Expect: 100-continue.
  20011. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20013. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20014. cli.Get("/second");
  20015. server_thread.join();
  20016. EXPECT_TRUE(closed_by_client);
  20017. }
  20018. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20019. // Long enough for the client to send Expect: 100-continue
  20020. with_single_response(
  20021. "HTTP/1.1 103 Early Hints\r\n"
  20022. "Link: </style.css>; rel=preload\r\n"
  20023. "\r\n"
  20024. "HTTP/1.1 401 Unauthorized\r\n"
  20025. "Content-Length: 0\r\n\r\n",
  20026. [](Client &cli) {
  20027. cli.set_read_timeout(2, 0);
  20028. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20030. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20031. });
  20032. }
  20033. #ifdef CPPHTTPLIB_SSL_ENABLED
  20034. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20035. #ifndef _WIN32
  20036. signal(SIGPIPE, SIG_IGN);
  20037. #endif
  20038. auto reused = false;
  20039. std::promise<int> port_promise;
  20040. auto server_thread = serve_single_response(
  20041. port_promise,
  20042. "HTTP/1.1 401 Unauthorized\r\n"
  20043. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20044. "Content-Length: 0\r\n\r\n",
  20045. [&](socket_t sock) {
  20046. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20047. char buf[256];
  20048. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20049. });
  20050. Client cli("127.0.0.1", port_promise.get_future().get());
  20051. cli.set_keep_alive(true);
  20052. cli.set_digest_auth("user", "pass");
  20053. cli.set_read_timeout(1, 0);
  20054. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20055. server_thread.join();
  20056. EXPECT_FALSE(reused);
  20057. }
  20058. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20059. // Any other answer to CONNECT would read as the origin's response.
  20060. struct {
  20061. const char *response;
  20062. bool passed_on;
  20063. } cases[] = {
  20064. {"HTTP/1.1 201 Created\r\n"
  20065. "Set-Cookie: session=from-proxy\r\n"
  20066. "Content-Length: 0\r\n\r\n",
  20067. false},
  20068. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20069. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20070. "Content-Length: 0\r\n\r\n",
  20071. true},
  20072. };
  20073. for (const auto &c : cases) {
  20074. std::promise<int> port_promise;
  20075. auto server_thread = serve_single_response(port_promise, c.response);
  20076. SSLClient cli("example.com", 443);
  20077. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20078. auto res = cli.Get("/");
  20079. server_thread.join();
  20080. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20081. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20082. if (res) {
  20083. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20084. }
  20085. }
  20086. }
  20087. #endif
  20088. // Records the client's error logger calls as "error METHOD path", or
  20089. // "error null" for a call without a request
  20090. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20091. return [&log](const Error &err, const Request *req) {
  20092. log.push_back(to_string(err) + " " +
  20093. (req ? req->method + " " + req->path : "null"));
  20094. };
  20095. }
  20096. // A failed request is reported once, with the request the caller made
  20097. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20098. Server svr;
  20099. svr.Get("/big", [](const Request &, Response &res) {
  20100. res.set_content(std::string(100000, 'b'), "text/plain");
  20101. });
  20102. auto port = svr.bind_to_any_port(HOST);
  20103. std::thread t([&]() { svr.listen_after_bind(); });
  20104. auto se = detail::scope_exit([&] {
  20105. svr.stop();
  20106. t.join();
  20107. });
  20108. svr.wait_until_ready();
  20109. Client cli(HOST, port);
  20110. std::vector<std::string> log;
  20111. cli.set_error_logger(record_errors(log));
  20112. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20113. cli.Get("/big", [](const char *, size_t) { return false; });
  20114. EXPECT_EQ(expected, log);
  20115. log.clear();
  20116. cli.Get("/big", [](size_t, size_t) { return false; });
  20117. EXPECT_EQ(expected, log);
  20118. }
  20119. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20120. // Fails while the body is read
  20121. auto broken = [](const Request &, Response &res) {
  20122. res.set_content_provider(10, "text/plain",
  20123. [](size_t, size_t, DataSink &) { return false; });
  20124. };
  20125. Server other;
  20126. other.Get("/broken", broken);
  20127. auto other_port = other.bind_to_any_port(HOST);
  20128. std::thread other_t([&]() { other.listen_after_bind(); });
  20129. auto other_se = detail::scope_exit([&] {
  20130. other.stop();
  20131. other_t.join();
  20132. });
  20133. other.wait_until_ready();
  20134. Server svr;
  20135. svr.Get("/broken", broken);
  20136. svr.Get("/same-origin",
  20137. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20138. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20139. res.set_redirect("http://" + std::string(HOST) + ":" +
  20140. std::to_string(other_port) + "/broken");
  20141. });
  20142. auto port = svr.bind_to_any_port(HOST);
  20143. std::thread t([&]() { svr.listen_after_bind(); });
  20144. auto se = detail::scope_exit([&] {
  20145. svr.stop();
  20146. t.join();
  20147. });
  20148. svr.wait_until_ready();
  20149. Client cli(HOST, port);
  20150. cli.set_follow_location(true);
  20151. std::vector<std::string> log;
  20152. cli.set_error_logger(record_errors(log));
  20153. for (auto path : {"/same-origin", "/cross-origin"}) {
  20154. log.clear();
  20155. auto res = cli.Get(path);
  20156. ASSERT_FALSE(res);
  20157. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20158. log);
  20159. }
  20160. }
  20161. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20162. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20163. std::vector<std::string> log;
  20164. cli.set_error_logger(record_errors(log));
  20165. auto handle = cli.open_stream("GET", "/x");
  20166. EXPECT_FALSE(handle.is_valid());
  20167. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20168. log);
  20169. });
  20170. }
  20171. #ifdef CPPHTTPLIB_SSL_ENABLED
  20172. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20173. // Not a TLS server, so the handshake fails. It waits for a request line in
  20174. // the handshake bytes, so a short read timeout lets it close quickly.
  20175. Server svr;
  20176. svr.set_read_timeout(0, 100000);
  20177. svr.Get("/x", [](const Request &, Response &res) {
  20178. res.set_content("x", "text/plain");
  20179. });
  20180. auto port = svr.bind_to_any_port(HOST);
  20181. std::thread t([&]() { svr.listen_after_bind(); });
  20182. auto se = detail::scope_exit([&] {
  20183. svr.stop();
  20184. t.join();
  20185. });
  20186. svr.wait_until_ready();
  20187. std::vector<std::string> log;
  20188. SSLClient cli(HOST, port);
  20189. cli.enable_server_certificate_verification(false);
  20190. cli.set_error_logger(record_errors(log));
  20191. auto res = cli.Get("/x");
  20192. ASSERT_FALSE(res);
  20193. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20194. log.clear();
  20195. auto handle = cli.open_stream("GET", "/x");
  20196. EXPECT_FALSE(handle.is_valid());
  20197. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20198. log.clear();
  20199. SSLClient no_ca(HOST, port);
  20200. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20201. no_ca.set_error_logger(record_errors(log));
  20202. res = no_ca.Get("/x");
  20203. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20204. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20205. }
  20206. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20207. #ifndef _WIN32
  20208. signal(SIGPIPE, SIG_IGN);
  20209. #endif
  20210. // Refused, answered with a challenge, or closed without an answer
  20211. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20212. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20213. "Content-Length: 0\r\n\r\n",
  20214. ""}) {
  20215. std::promise<int> port_promise;
  20216. auto server_thread = serve_single_response(port_promise, response);
  20217. SSLClient cli("example.com", 443);
  20218. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20219. std::vector<std::string> log;
  20220. cli.set_error_logger(record_errors(log));
  20221. auto res = cli.Get("/");
  20222. server_thread.join();
  20223. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20224. << response;
  20225. }
  20226. }
  20227. #endif
  20228. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20229. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20230. // the chunked coding and drop Content-Length, so a front-end that trusts
  20231. // Content-Length would disagree about where the body ends (response
  20232. // smuggling). The client must reject such a response.
  20233. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20234. for (const char *te : {"chunked", "gzip, chunked"}) {
  20235. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20236. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20237. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20238. "5\r\nhello\r\n0\r\n\r\n";
  20239. with_single_response(response, [&](Client &cli) {
  20240. auto res = cli.Get("/");
  20241. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20242. EXPECT_EQ(Error::Read, res.error()) << te;
  20243. });
  20244. with_single_response(response, [&](Client &cli) {
  20245. auto handle = cli.open_stream("GET", "/");
  20246. EXPECT_FALSE(handle.is_valid()) << te;
  20247. EXPECT_EQ(Error::Read, handle.error) << te;
  20248. });
  20249. }
  20250. }
  20251. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20252. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20253. // closing the connection (unlike a request, which must be rejected).
  20254. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20255. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20256. "Transfer-Encoding: chunked\r\n"
  20257. "Connection: close\r\n"
  20258. "\r\n"
  20259. "5\r\nhello\r\n0\r\n\r\n",
  20260. "HTTP/1.1 200 OK\r\n"
  20261. "Transfer-Encoding: gzip\r\n"
  20262. "Connection: close\r\n"
  20263. "\r\n"
  20264. "hello"}) {
  20265. with_single_response(response, [&](Client &cli) {
  20266. auto res = cli.Get("/");
  20267. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20268. EXPECT_EQ("hello", res->body);
  20269. });
  20270. with_single_response(response, [&](Client &cli) {
  20271. auto handle = cli.open_stream("GET", "/");
  20272. ASSERT_TRUE(handle.is_valid()) << response;
  20273. EXPECT_EQ("hello", read_all(handle));
  20274. });
  20275. }
  20276. }
  20277. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20278. // framing headers describe nothing to read and must not be rejected.
  20279. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20280. const std::string framing = "Content-Length: 5\r\n"
  20281. "Transfer-Encoding: chunked\r\n"
  20282. "Connection: close\r\n"
  20283. "\r\n";
  20284. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20285. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20286. });
  20287. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20288. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20289. });
  20290. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20291. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20292. with_single_response(response, [&](Client &cli) {
  20293. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20294. });
  20295. with_single_response(response, [&](Client &cli) {
  20296. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20297. });
  20298. }
  20299. }
  20300. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20301. // header section, so a stream opened on one has nothing to read, whatever
  20302. // framing or coding headers it carries.
  20303. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20304. struct Case {
  20305. const char *method;
  20306. const char *status;
  20307. };
  20308. // A reader of the declared body reports an early close when nothing
  20309. // follows, and hands back what does.
  20310. struct Framing {
  20311. const char *headers;
  20312. const char *after;
  20313. };
  20314. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20315. Case{"GET", "304 Not Modified"}}) {
  20316. for (const auto &f :
  20317. {Framing{"Content-Length: 5\r\n", ""},
  20318. Framing{"Content-Length: 5\r\n", "hello"},
  20319. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20320. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20321. // Not decoded, so a build without Brotli opens it too
  20322. Framing{"Content-Encoding: br\r\n", ""}}) {
  20323. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20324. "Connection: close\r\n"
  20325. "\r\n" +
  20326. f.after;
  20327. with_single_response(response, [&](Client &cli) {
  20328. auto handle = cli.open_stream(c.method, "/");
  20329. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20330. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20331. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20332. });
  20333. }
  20334. }
  20335. }
  20336. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20337. // response, is faulty framing, so the connection is not reused after it.
  20338. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20339. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20340. "Content-Length: 0\r\n"
  20341. "Transfer-Encoding: chunked\r\n"
  20342. "\r\n"
  20343. "5\r\nhello\r\n0\r\n\r\n",
  20344. "HTTP/1.0 200 Connection established\r\n"
  20345. "Connection: keep-alive\r\n"
  20346. "Transfer-Encoding: chunked\r\n"
  20347. "\r\n"
  20348. "5\r\nhello\r\n0\r\n\r\n"}) {
  20349. with_single_response(response, [&](Client &cli) {
  20350. cli.set_keep_alive(true);
  20351. auto res = cli.Get("/");
  20352. ASSERT_TRUE(res) << response;
  20353. EXPECT_EQ("hello", res->body);
  20354. EXPECT_FALSE(cli.is_socket_open()) << response;
  20355. });
  20356. }
  20357. }
  20358. // A payload max length of 0 means no limit, however the body is framed.
  20359. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20360. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20361. "Transfer-Encoding: chunked\r\n"
  20362. "\r\n"
  20363. "5\r\nhello\r\n0\r\n\r\n",
  20364. "HTTP/1.1 200 OK\r\n"
  20365. "Connection: close\r\n"
  20366. "\r\n"
  20367. "hello"}) {
  20368. with_single_response(response, [&](Client &cli) {
  20369. cli.set_payload_max_length(0);
  20370. auto res = cli.Get("/");
  20371. ASSERT_TRUE(res) << response;
  20372. EXPECT_EQ("hello", res->body) << response;
  20373. });
  20374. }
  20375. }
  20376. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20377. Server svr;
  20378. svr.set_payload_max_length(0);
  20379. svr.Post("/echo", [](const Request &req, Response &res) {
  20380. res.set_content(req.body, "text/plain");
  20381. });
  20382. auto port = svr.bind_to_any_port(HOST);
  20383. thread t = thread([&] { svr.listen_after_bind(); });
  20384. auto se = detail::scope_exit([&] {
  20385. svr.stop();
  20386. t.join();
  20387. ASSERT_FALSE(svr.is_running());
  20388. });
  20389. svr.wait_until_ready();
  20390. Client cli(HOST, port);
  20391. auto res = cli.Post(
  20392. "/echo",
  20393. [](size_t /*offset*/, DataSink &sink) {
  20394. sink.write("hello", 5);
  20395. sink.done();
  20396. return true;
  20397. },
  20398. "text/plain");
  20399. ASSERT_TRUE(res);
  20400. EXPECT_EQ(StatusCode::OK_200, res->status);
  20401. EXPECT_EQ("hello", res->body);
  20402. }
  20403. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20404. TEST_F(OpenStreamTest, Gzip) {
  20405. Client cli("127.0.0.1", port_);
  20406. auto handle = cli.open_stream("GET", "/compressible", {},
  20407. {{"Accept-Encoding", "gzip"}});
  20408. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20409. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20410. }
  20411. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20412. Client cli("127.0.0.1", port_);
  20413. auto handle =
  20414. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20415. {{"Accept-Encoding", "gzip"}});
  20416. ASSERT_TRUE(handle.is_valid());
  20417. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20418. EXPECT_EQ("123456789", read_all(handle));
  20419. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20420. }
  20421. #endif
  20422. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20423. TEST_F(OpenStreamTest, Brotli) {
  20424. Client cli("127.0.0.1", port_);
  20425. auto handle =
  20426. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20427. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20428. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20429. }
  20430. #endif
  20431. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20432. TEST_F(OpenStreamTest, Zstd) {
  20433. Client cli("127.0.0.1", port_);
  20434. auto handle = cli.open_stream("GET", "/compressible", {},
  20435. {{"Accept-Encoding", "zstd"}});
  20436. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20437. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20438. }
  20439. #endif
  20440. #ifdef CPPHTTPLIB_SSL_ENABLED
  20441. class SSLOpenStreamTest : public ::testing::Test {
  20442. protected:
  20443. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20444. void SetUp() override {
  20445. svr_.Get("/hello", [](const Request &, Response &res) {
  20446. res.set_content("Hello SSL World!", "text/plain");
  20447. });
  20448. svr_.Get("/chunked", [](const Request &, Response &res) {
  20449. res.set_chunked_content_provider("text/plain",
  20450. [](size_t offset, DataSink &sink) {
  20451. if (offset < 15) {
  20452. sink.write("chunk", 5);
  20453. return true;
  20454. }
  20455. sink.done();
  20456. return true;
  20457. });
  20458. });
  20459. svr_.Post("/echo", [](const Request &req, Response &res) {
  20460. res.set_content(req.body, req.get_header_value("Content-Type"));
  20461. });
  20462. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20463. std::string body = req.body;
  20464. res.set_chunked_content_provider(
  20465. "text/plain", [body](size_t offset, DataSink &sink) {
  20466. if (offset < body.size()) {
  20467. sink.write(body.data() + offset, body.size() - offset);
  20468. }
  20469. sink.done();
  20470. return true;
  20471. });
  20472. });
  20473. port_ = svr_.bind_to_any_port("127.0.0.1");
  20474. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20475. svr_.wait_until_ready();
  20476. }
  20477. void TearDown() override {
  20478. svr_.stop();
  20479. if (thread_.joinable()) thread_.join();
  20480. }
  20481. SSLServer svr_;
  20482. std::thread thread_;
  20483. int port_ = 0;
  20484. };
  20485. TEST_F(SSLOpenStreamTest, Basic) {
  20486. SSLClient cli("127.0.0.1", port_);
  20487. cli.enable_server_certificate_verification(false);
  20488. auto handle = cli.open_stream("GET", "/hello");
  20489. ASSERT_TRUE(handle.is_valid());
  20490. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20491. }
  20492. TEST_F(SSLOpenStreamTest, Chunked) {
  20493. SSLClient cli("127.0.0.1", port_);
  20494. cli.enable_server_certificate_verification(false);
  20495. auto handle = cli.open_stream("GET", "/chunked");
  20496. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20497. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20498. "Transfer-Encoding") == "chunked");
  20499. auto body = read_all(handle);
  20500. EXPECT_EQ("chunkchunkchunk", body);
  20501. }
  20502. TEST_F(SSLOpenStreamTest, Post) {
  20503. SSLClient cli("127.0.0.1", port_);
  20504. cli.enable_server_certificate_verification(false);
  20505. auto handle =
  20506. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20507. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20508. EXPECT_EQ(200, handle.response->status);
  20509. auto body = read_all(handle);
  20510. EXPECT_EQ("Hello SSL POST", body);
  20511. }
  20512. TEST_F(SSLOpenStreamTest, PostChunked) {
  20513. SSLClient cli("127.0.0.1", port_);
  20514. cli.enable_server_certificate_verification(false);
  20515. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20516. "Chunked SSL Data", "text/plain");
  20517. ASSERT_TRUE(handle.is_valid());
  20518. EXPECT_EQ(200, handle.response->status);
  20519. auto body = read_all(handle);
  20520. EXPECT_EQ("Chunked SSL Data", body);
  20521. }
  20522. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20523. // Content-Length is terminated by the server closing the connection. When the
  20524. // SSL peer sends a close_notify after the body, the client must treat it as a
  20525. // clean EOF and return a successful response rather than an error.
  20526. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20528. ASSERT_TRUE(svr.is_valid());
  20529. svr.set_keep_alive_max_count(1);
  20530. const std::string expected_body = "Hello from connection-close response!";
  20531. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20532. res.set_content_provider("text/plain",
  20533. [&](size_t offset, DataSink &sink) -> bool {
  20534. if (offset < expected_body.size()) {
  20535. sink.write(expected_body.data() + offset,
  20536. expected_body.size() - offset);
  20537. }
  20538. sink.done();
  20539. return true;
  20540. });
  20541. });
  20542. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20543. auto se = detail::scope_exit([&] {
  20544. svr.stop();
  20545. listen_thread.join();
  20546. ASSERT_FALSE(svr.is_running());
  20547. });
  20548. svr.wait_until_ready();
  20549. SSLClient cli(HOST, PORT);
  20550. cli.enable_server_certificate_verification(false);
  20551. auto res = cli.Get("/no-content-length");
  20552. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20553. EXPECT_EQ(StatusCode::OK_200, res->status);
  20554. EXPECT_EQ(expected_body, res->body);
  20555. }
  20556. #endif // CPPHTTPLIB_SSL_ENABLED
  20557. //==============================================================================
  20558. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20559. // results for various scenarios.
  20560. //==============================================================================
  20561. TEST(ParityTest, GetVsOpenStream) {
  20562. Server svr;
  20563. const std::string path = "/parity";
  20564. const std::string content = "Parity test content: hello world";
  20565. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20566. res.set_content(content, "text/plain");
  20567. });
  20568. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20569. auto se = detail::scope_exit([&] {
  20570. svr.stop();
  20571. t.join();
  20572. ASSERT_FALSE(svr.is_running());
  20573. });
  20574. svr.wait_until_ready();
  20575. Client cli(HOST, PORT);
  20576. // Non-stream path
  20577. auto r1 = cli.Get(path);
  20578. ASSERT_TRUE(r1);
  20579. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20580. // Stream path
  20581. auto h = cli.open_stream("GET", path);
  20582. ASSERT_TRUE(h.is_valid());
  20583. EXPECT_EQ(r1->body, read_all(h));
  20584. }
  20585. // Helper to compress data with provided compressor type T
  20586. template <typename Compressor>
  20587. static std::string compress_payload_for_parity(const std::string &in) {
  20588. std::string out;
  20589. Compressor compressor;
  20590. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20591. [&](const char *data, size_t n) {
  20592. out.append(data, n);
  20593. return true;
  20594. });
  20595. EXPECT_TRUE(ok);
  20596. return out;
  20597. }
  20598. // Helper function for compression parity tests
  20599. template <typename Compressor>
  20600. static void test_compression_parity(const std::string &original,
  20601. const std::string &path,
  20602. const std::string &encoding) {
  20603. const std::string compressed =
  20604. compress_payload_for_parity<Compressor>(original);
  20605. Server svr;
  20606. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20607. res.set_content(compressed, "application/octet-stream");
  20608. res.set_header("Content-Encoding", encoding);
  20609. });
  20610. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20611. auto se = detail::scope_exit([&] {
  20612. svr.stop();
  20613. t.join();
  20614. ASSERT_FALSE(svr.is_running());
  20615. });
  20616. svr.wait_until_ready();
  20617. Client cli(HOST, PORT);
  20618. // Non-streaming
  20619. {
  20620. auto res = cli.Get(path);
  20621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20622. EXPECT_EQ(StatusCode::OK_200, res->status);
  20623. EXPECT_EQ(original, res->body);
  20624. }
  20625. // Streaming
  20626. {
  20627. auto h = cli.open_stream("GET", path);
  20628. ASSERT_TRUE(h.is_valid());
  20629. EXPECT_EQ(original, read_all(h));
  20630. }
  20631. }
  20632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20633. TEST(ParityTest, Gzip) {
  20634. test_compression_parity<detail::gzip_compressor>(
  20635. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20636. }
  20637. #endif
  20638. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20639. TEST(ParityTest, Brotli) {
  20640. test_compression_parity<detail::brotli_compressor>(
  20641. "Hello, brotli parity test payload", "/parity-br", "br");
  20642. }
  20643. #endif
  20644. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20645. TEST(ParityTest, Zstd) {
  20646. test_compression_parity<detail::zstd_compressor>(
  20647. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20648. }
  20649. #endif
  20650. //==============================================================================
  20651. // New Stream API Tests
  20652. //==============================================================================
  20653. inline std::string read_body(httplib::stream::Result &result) {
  20654. std::string body;
  20655. while (result.next()) {
  20656. body.append(result.data(), result.size());
  20657. }
  20658. return body;
  20659. }
  20660. TEST(ClientConnectionTest, Basic) {
  20661. httplib::ClientConnection conn;
  20662. EXPECT_FALSE(conn.is_open());
  20663. conn.sock = 1;
  20664. EXPECT_TRUE(conn.is_open());
  20665. httplib::ClientConnection conn2(std::move(conn));
  20666. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20667. conn2.sock = INVALID_SOCKET;
  20668. }
  20669. // Unified test server for all stream::* tests
  20670. class StreamApiTest : public ::testing::Test {
  20671. protected:
  20672. void SetUp() override {
  20673. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20674. res.set_content("Hello World!", "text/plain");
  20675. });
  20676. svr_.Get("/echo-params",
  20677. [](const httplib::Request &req, httplib::Response &res) {
  20678. std::string r;
  20679. for (const auto &p : req.params) {
  20680. if (!r.empty()) r += "&";
  20681. r += p.first + "=" + p.second;
  20682. }
  20683. res.set_content(r, "text/plain");
  20684. });
  20685. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20686. res.set_content(req.body, req.get_header_value("Content-Type"));
  20687. });
  20688. svr_.Post("/echo-headers",
  20689. [](const httplib::Request &req, httplib::Response &res) {
  20690. std::string r;
  20691. for (const auto &h : req.headers)
  20692. r += h.first + ": " + h.second + "\n";
  20693. res.set_content(r, "text/plain");
  20694. });
  20695. svr_.Post("/echo-params",
  20696. [](const httplib::Request &req, httplib::Response &res) {
  20697. std::string r = "params:";
  20698. for (const auto &p : req.params)
  20699. r += p.first + "=" + p.second + ";";
  20700. res.set_content(r + " body:" + req.body, "text/plain");
  20701. });
  20702. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20703. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20704. });
  20705. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20706. res.set_content("PUT:" + req.body, "text/plain");
  20707. });
  20708. svr_.Patch("/echo",
  20709. [](const httplib::Request &req, httplib::Response &res) {
  20710. res.set_content("PATCH:" + req.body, "text/plain");
  20711. });
  20712. svr_.Delete(
  20713. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20714. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20715. "text/plain");
  20716. });
  20717. svr_.Get("/head-test",
  20718. [](const httplib::Request &, httplib::Response &res) {
  20719. res.set_content("body for HEAD", "text/plain");
  20720. });
  20721. svr_.Options("/options",
  20722. [](const httplib::Request &, httplib::Response &res) {
  20723. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20724. });
  20725. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20726. svr_.wait_until_ready();
  20727. }
  20728. void TearDown() override {
  20729. svr_.stop();
  20730. if (thread_.joinable()) thread_.join();
  20731. }
  20732. httplib::Server svr_;
  20733. std::thread thread_;
  20734. };
  20735. // stream::Get tests
  20736. TEST_F(StreamApiTest, GetBasic) {
  20737. httplib::Client cli(HOST, PORT);
  20738. auto result = httplib::stream::Get(cli, "/hello");
  20739. ASSERT_TRUE(result.is_valid());
  20740. EXPECT_EQ(200, result.status());
  20741. EXPECT_EQ("Hello World!", read_body(result));
  20742. }
  20743. TEST_F(StreamApiTest, GetWithParams) {
  20744. httplib::Client cli(HOST, PORT);
  20745. httplib::Params params{{"foo", "bar"}};
  20746. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20747. ASSERT_TRUE(result.is_valid());
  20748. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20749. }
  20750. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20751. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20752. httplib::Client cli(HOST, PORT);
  20753. cli.set_payload_max_length(0);
  20754. auto result = httplib::stream::Get(cli, "/hello");
  20755. ASSERT_TRUE(result.is_valid());
  20756. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20757. EXPECT_EQ("Hello World!", read_body(result));
  20758. }
  20759. #endif
  20760. TEST_F(StreamApiTest, GetConnectionError) {
  20761. httplib::Client cli(HOST, 9999);
  20762. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20763. }
  20764. TEST_F(StreamApiTest, Get404) {
  20765. httplib::Client cli(HOST, PORT);
  20766. auto result = httplib::stream::Get(cli, "/nonexistent");
  20767. EXPECT_TRUE(result.is_valid());
  20768. EXPECT_EQ(404, result.status());
  20769. }
  20770. // stream::Post tests
  20771. TEST_F(StreamApiTest, PostBasic) {
  20772. httplib::Client cli(HOST, PORT);
  20773. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20774. "application/json");
  20775. ASSERT_TRUE(result.is_valid());
  20776. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20777. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20778. }
  20779. TEST_F(StreamApiTest, PostWithHeaders) {
  20780. httplib::Client cli(HOST, PORT);
  20781. httplib::Headers headers{{"X-Custom", "value"}};
  20782. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20783. "text/plain");
  20784. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20785. }
  20786. TEST_F(StreamApiTest, PostWithParams) {
  20787. httplib::Client cli(HOST, PORT);
  20788. httplib::Params params{{"k", "v"}};
  20789. auto result =
  20790. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20791. auto body = read_body(result);
  20792. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20793. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20794. }
  20795. TEST_F(StreamApiTest, PostLarge) {
  20796. httplib::Client cli(HOST, PORT);
  20797. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20798. size_t total = 0;
  20799. while (result.next()) {
  20800. total += result.size();
  20801. }
  20802. EXPECT_EQ(100u * 1024u, total);
  20803. }
  20804. // stream::Put/Patch tests
  20805. TEST_F(StreamApiTest, PutAndPatch) {
  20806. httplib::Client cli(HOST, PORT);
  20807. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20808. EXPECT_EQ("PUT:test", read_body(put));
  20809. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20810. EXPECT_EQ("PATCH:test", read_body(patch));
  20811. }
  20812. // stream::Delete tests
  20813. TEST_F(StreamApiTest, Delete) {
  20814. httplib::Client cli(HOST, PORT);
  20815. auto del1 = httplib::stream::Delete(cli, "/resource");
  20816. EXPECT_EQ("Deleted", read_body(del1));
  20817. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20818. EXPECT_EQ("Deleted:data", read_body(del2));
  20819. }
  20820. // stream::Head/Options tests
  20821. TEST_F(StreamApiTest, HeadAndOptions) {
  20822. httplib::Client cli(HOST, PORT);
  20823. auto head = httplib::stream::Head(cli, "/head-test");
  20824. EXPECT_TRUE(head.is_valid());
  20825. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20826. auto opts = httplib::stream::Options(cli, "/options");
  20827. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20828. }
  20829. // SSL stream::* tests
  20830. #ifdef CPPHTTPLIB_SSL_ENABLED
  20831. class SSLStreamApiTest : public ::testing::Test {
  20832. protected:
  20833. void SetUp() override {
  20834. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20835. res.set_content("Hello SSL!", "text/plain");
  20836. });
  20837. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20838. res.set_content(req.body, "text/plain");
  20839. });
  20840. port_ = svr_.bind_to_any_port("127.0.0.1");
  20841. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20842. svr_.wait_until_ready();
  20843. }
  20844. void TearDown() override {
  20845. svr_.stop();
  20846. if (thread_.joinable()) thread_.join();
  20847. }
  20848. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20849. std::thread thread_;
  20850. int port_ = 0;
  20851. };
  20852. TEST_F(SSLStreamApiTest, GetAndPost) {
  20853. httplib::SSLClient cli("127.0.0.1", port_);
  20854. cli.enable_server_certificate_verification(false);
  20855. auto get = httplib::stream::Get(cli, "/hello");
  20856. EXPECT_EQ("Hello SSL!", read_body(get));
  20857. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20858. EXPECT_EQ("test", read_body(post));
  20859. }
  20860. #endif
  20861. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20862. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20863. // BodyReader
  20864. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20865. // Test that read timeout during streaming is detected
  20866. // Use a large content-length response where server delays mid-stream
  20867. Server svr;
  20868. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20869. // Send a large response with delay in the middle
  20870. res.set_content_provider(
  20871. 1000, // content_length
  20872. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20873. if (offset < 100) {
  20874. // Send first 100 bytes immediately
  20875. std::string data(100, 'A');
  20876. sink.write(data.c_str(), data.size());
  20877. return true;
  20878. }
  20879. // Then delay longer than client timeout
  20880. std::this_thread::sleep_for(std::chrono::seconds(3));
  20881. std::string data(900, 'B');
  20882. sink.write(data.c_str(), data.size());
  20883. return true;
  20884. });
  20885. });
  20886. auto port = 8091;
  20887. std::thread t([&]() { svr.listen("localhost", port); });
  20888. svr.wait_until_ready();
  20889. Client cli("localhost", port);
  20890. cli.set_read_timeout(1, 0); // 1 second timeout
  20891. auto handle = cli.open_stream("GET", "/slow-stream");
  20892. ASSERT_TRUE(handle.is_valid());
  20893. char buf[256];
  20894. ssize_t total = 0;
  20895. ssize_t n;
  20896. bool got_error = false;
  20897. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20898. total += n;
  20899. }
  20900. if (n < 0) {
  20901. got_error = true;
  20902. // Should be timeout or read error
  20903. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20904. handle.get_read_error() == Error::Read)
  20905. << "Actual error: " << to_string(handle.get_read_error());
  20906. }
  20907. // Either we got an error, or we got less data than expected
  20908. EXPECT_TRUE(got_error || total < 1000)
  20909. << "Expected timeout but got all " << total << " bytes";
  20910. svr.stop();
  20911. t.join();
  20912. }
  20913. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20914. // Test connection closed detection via BodyReader
  20915. Server svr;
  20916. std::atomic<bool> close_now{false};
  20917. svr.Get("/will-close", [&](const Request &, Response &res) {
  20918. res.set_content_provider(
  20919. 10000, // Large content_length that we won't fully send
  20920. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20921. if (offset < 100) {
  20922. std::string data(100, 'X');
  20923. sink.write(data.c_str(), data.size());
  20924. return true;
  20925. }
  20926. // Wait for signal then abort
  20927. while (!close_now) {
  20928. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20929. }
  20930. return false; // Abort - server will close connection
  20931. });
  20932. });
  20933. auto port = 8092;
  20934. std::thread t([&]() { svr.listen("localhost", port); });
  20935. svr.wait_until_ready();
  20936. Client cli("localhost", port);
  20937. auto handle = cli.open_stream("GET", "/will-close");
  20938. ASSERT_TRUE(handle.is_valid());
  20939. char buf[256];
  20940. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20941. EXPECT_GT(n, 0) << "First read should succeed";
  20942. // Signal server to close
  20943. close_now = true;
  20944. // Keep reading until error or EOF
  20945. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20946. // Keep reading
  20947. }
  20948. // Should get an error since content_length wasn't satisfied
  20949. if (n < 0) {
  20950. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20951. handle.get_read_error() == Error::Read)
  20952. << "Actual error: " << to_string(handle.get_read_error());
  20953. }
  20954. svr.stop();
  20955. t.join();
  20956. }
  20957. #ifdef CPPHTTPLIB_SSL_ENABLED
  20958. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20959. // Test that read timeout during SSL streaming is detected
  20960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20961. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20962. res.set_content_provider(
  20963. 1000, "text/plain",
  20964. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20965. if (offset < 100) {
  20966. std::string data(100, 'A');
  20967. sink.write(data.c_str(), data.size());
  20968. return true;
  20969. }
  20970. std::this_thread::sleep_for(std::chrono::seconds(3));
  20971. std::string data(900, 'B');
  20972. sink.write(data.c_str(), data.size());
  20973. return true;
  20974. });
  20975. });
  20976. auto port = 8093;
  20977. std::thread t([&]() { svr.listen("localhost", port); });
  20978. svr.wait_until_ready();
  20979. SSLClient cli("localhost", port);
  20980. cli.enable_server_certificate_verification(false);
  20981. cli.set_read_timeout(1, 0); // 1 second timeout
  20982. auto handle = cli.open_stream("GET", "/slow-stream");
  20983. ASSERT_TRUE(handle.is_valid());
  20984. char buf[256];
  20985. ssize_t total = 0;
  20986. ssize_t n;
  20987. bool got_error = false;
  20988. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20989. total += n;
  20990. }
  20991. if (n < 0) {
  20992. got_error = true;
  20993. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20994. handle.get_read_error() == Error::Read)
  20995. << "Actual error: " << to_string(handle.get_read_error());
  20996. }
  20997. EXPECT_TRUE(got_error || total < 1000)
  20998. << "Expected timeout but got all " << total << " bytes";
  20999. svr.stop();
  21000. t.join();
  21001. }
  21002. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21003. // Test SSL connection closed detection
  21004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21005. std::atomic<bool> close_now{false};
  21006. svr.Get("/will-close", [&](const Request &, Response &res) {
  21007. res.set_content_provider(
  21008. 10000, "text/plain",
  21009. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21010. if (offset < 100) {
  21011. std::string data(100, 'X');
  21012. sink.write(data.c_str(), data.size());
  21013. return true;
  21014. }
  21015. while (!close_now) {
  21016. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21017. }
  21018. return false;
  21019. });
  21020. });
  21021. auto port = 8094;
  21022. std::thread t([&]() { svr.listen("localhost", port); });
  21023. svr.wait_until_ready();
  21024. SSLClient cli("localhost", port);
  21025. cli.enable_server_certificate_verification(false);
  21026. auto handle = cli.open_stream("GET", "/will-close");
  21027. ASSERT_TRUE(handle.is_valid());
  21028. char buf[256];
  21029. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21030. EXPECT_GT(n, 0);
  21031. // Signal server to close
  21032. close_now = true;
  21033. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21034. // Keep reading
  21035. }
  21036. if (n < 0) {
  21037. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21038. handle.get_read_error() == Error::Read)
  21039. << "Actual error: " << to_string(handle.get_read_error());
  21040. }
  21041. svr.stop();
  21042. t.join();
  21043. }
  21044. #endif
  21045. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21046. using namespace httplib;
  21047. // Create a test file
  21048. const char *fname = "etag_testfile.txt";
  21049. const char *content = "etag-content";
  21050. {
  21051. std::ofstream ofs(fname);
  21052. ofs << content;
  21053. ASSERT_TRUE(ofs.good());
  21054. }
  21055. Server svr;
  21056. svr.set_mount_point("/static", ".");
  21057. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21058. svr.wait_until_ready();
  21059. Client cli(HOST, PORT);
  21060. // First request: should get 200 with ETag header
  21061. auto res1 = cli.Get("/static/etag_testfile.txt");
  21062. ASSERT_TRUE(res1);
  21063. ASSERT_EQ(200, res1->status);
  21064. ASSERT_TRUE(res1->has_header("ETag"));
  21065. std::string etag = res1->get_header_value("ETag");
  21066. EXPECT_FALSE(etag.empty());
  21067. // Verify ETag format: W/"hex-hex"
  21068. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21069. EXPECT_EQ('W', etag[0]);
  21070. EXPECT_EQ('/', etag[1]);
  21071. EXPECT_EQ('"', etag[2]);
  21072. EXPECT_EQ('"', etag.back());
  21073. // Exact match: expect 304 Not Modified
  21074. Headers h2 = {{"If-None-Match", etag}};
  21075. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21076. ASSERT_TRUE(res2);
  21077. EXPECT_EQ(304, res2->status);
  21078. // Wildcard match: expect 304 Not Modified
  21079. Headers h3 = {{"If-None-Match", "*"}};
  21080. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21081. ASSERT_TRUE(res3);
  21082. EXPECT_EQ(304, res3->status);
  21083. // Non-matching ETag: expect 200
  21084. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21085. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21086. ASSERT_TRUE(res4);
  21087. EXPECT_EQ(200, res4->status);
  21088. // Multiple ETags with one matching: expect 304
  21089. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21090. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21091. ASSERT_TRUE(res5);
  21092. EXPECT_EQ(304, res5->status);
  21093. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21094. // that equivalent to the single comma-separated list above, so the match on
  21095. // the second line must still be found.
  21096. Headers h6;
  21097. h6.emplace("If-None-Match", "W/\"other\"");
  21098. h6.emplace("If-None-Match", etag);
  21099. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21100. ASSERT_TRUE(res6);
  21101. EXPECT_EQ(304, res6->status);
  21102. svr.stop();
  21103. t.join();
  21104. std::remove(fname);
  21105. }
  21106. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21107. using namespace httplib;
  21108. Server svr;
  21109. svr.set_mount_point("/static", ".");
  21110. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21111. svr.wait_until_ready();
  21112. Client cli(HOST, PORT);
  21113. // Send If-None-Match: * to a non-existent file
  21114. Headers h = {{"If-None-Match", "*"}};
  21115. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21117. EXPECT_EQ(404, res->status);
  21118. svr.stop();
  21119. t.join();
  21120. }
  21121. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21122. using namespace httplib;
  21123. // Create a test file
  21124. const char *fname = "etag_boundary_testfile.txt";
  21125. const char *content = "boundary-test";
  21126. {
  21127. std::ofstream ofs(fname);
  21128. ofs << content;
  21129. ASSERT_TRUE(ofs.good());
  21130. }
  21131. Server svr;
  21132. svr.set_mount_point("/static", ".");
  21133. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21134. svr.wait_until_ready();
  21135. Client cli(HOST, PORT);
  21136. // Get the actual ETag
  21137. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21138. ASSERT_TRUE(res1);
  21139. ASSERT_EQ(200, res1->status);
  21140. ASSERT_TRUE(res1->has_header("ETag"));
  21141. std::string etag = res1->get_header_value("ETag");
  21142. // Test 1: Very long ETag value (longer than actual ETag)
  21143. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21144. Headers h1 = {{"If-None-Match", "W/"
  21145. "\"very-long-etag-value-that-is-much-longer-"
  21146. "than-the-actual-etag-value\""}};
  21147. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21148. ASSERT_TRUE(res2);
  21149. EXPECT_EQ(200, res2->status); // Should not match
  21150. // Test 2: Long string followed by wildcard
  21151. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21152. // string)
  21153. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21154. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21155. ASSERT_TRUE(res3);
  21156. EXPECT_EQ(304, res3->status); // Should match on "*"
  21157. // Test 3: Wildcard followed by long string
  21158. // Should match on "*" immediately and return 304
  21159. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21160. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21161. ASSERT_TRUE(res4);
  21162. EXPECT_EQ(304, res4->status); // Should match on "*"
  21163. // Test 4: Multiple long non-matching values
  21164. // Should NOT match and return 200 (test that all comparisons are safe)
  21165. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21166. "W/\"second-long-non-matching-value\", "
  21167. "W/\"third-long-non-matching-value\""}};
  21168. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21169. ASSERT_TRUE(res5);
  21170. EXPECT_EQ(200, res5->status); // Should not match
  21171. // Test 5: Single character that is not "*" (edge case)
  21172. Headers h5 = {{"If-None-Match", "X"}};
  21173. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21174. ASSERT_TRUE(res6);
  21175. EXPECT_EQ(200, res6->status); // Should not match
  21176. svr.stop();
  21177. t.join();
  21178. std::remove(fname);
  21179. }
  21180. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21181. using namespace httplib;
  21182. // Create a test file
  21183. const char *fname = "ims_testfile.txt";
  21184. const char *content = "if-modified-since-test";
  21185. {
  21186. std::ofstream ofs(fname);
  21187. ofs << content;
  21188. ASSERT_TRUE(ofs.good());
  21189. }
  21190. Server svr;
  21191. svr.set_mount_point("/static", ".");
  21192. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21193. svr.wait_until_ready();
  21194. Client cli(HOST, PORT);
  21195. // First request: should get 200 with Last-Modified header
  21196. auto res1 = cli.Get("/static/ims_testfile.txt");
  21197. ASSERT_TRUE(res1);
  21198. ASSERT_EQ(200, res1->status);
  21199. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21200. std::string last_modified = res1->get_header_value("Last-Modified");
  21201. EXPECT_FALSE(last_modified.empty());
  21202. // If-Modified-Since with same time: expect 304
  21203. Headers h2 = {{"If-Modified-Since", last_modified}};
  21204. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21205. ASSERT_TRUE(res2);
  21206. EXPECT_EQ(304, res2->status);
  21207. // If-Modified-Since with future time: expect 304
  21208. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21209. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21210. ASSERT_TRUE(res3);
  21211. EXPECT_EQ(304, res3->status);
  21212. // If-Modified-Since with past time: expect 200
  21213. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21214. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21215. ASSERT_TRUE(res4);
  21216. EXPECT_EQ(200, res4->status);
  21217. // If-None-Match takes precedence over If-Modified-Since
  21218. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21219. ASSERT_TRUE(res1->has_header("ETag"));
  21220. std::string etag = res1->get_header_value("ETag");
  21221. Headers h5 = {{"If-None-Match", etag},
  21222. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21223. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21224. ASSERT_TRUE(res5);
  21225. EXPECT_EQ(304, res5->status);
  21226. svr.stop();
  21227. t.join();
  21228. std::remove(fname);
  21229. }
  21230. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21231. using namespace httplib;
  21232. Server svr;
  21233. // Endpoint that returns compressible content
  21234. svr.Get("/compressible", [](const Request &, Response &res) {
  21235. // Return a large enough body to trigger compression
  21236. std::string body(1000, 'a');
  21237. res.set_content(body, "text/plain");
  21238. });
  21239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21240. svr.wait_until_ready();
  21241. Client cli(HOST, PORT);
  21242. // Request with gzip support: should get Vary header when compressed
  21243. cli.set_compress(true);
  21244. auto res1 = cli.Get("/compressible");
  21245. ASSERT_TRUE(res1);
  21246. EXPECT_EQ(200, res1->status);
  21247. // If Content-Encoding is set, Vary should also be set
  21248. if (res1->has_header("Content-Encoding")) {
  21249. EXPECT_TRUE(res1->has_header("Vary"));
  21250. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21251. }
  21252. // Request without Accept-Encoding header: should not have compression
  21253. Headers h_no_compress;
  21254. auto res2 = cli.Get("/compressible", h_no_compress);
  21255. ASSERT_TRUE(res2);
  21256. EXPECT_EQ(200, res2->status);
  21257. // Verify Vary header is present when compression is applied
  21258. // (the exact behavior depends on server configuration)
  21259. svr.stop();
  21260. t.join();
  21261. }
  21262. TEST(ETagTest, IfRangeWithETag) {
  21263. using namespace httplib;
  21264. // Create a test file with known content
  21265. const char *fname = "if_range_testfile.txt";
  21266. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21267. {
  21268. std::ofstream ofs(fname);
  21269. ofs << content;
  21270. ASSERT_TRUE(ofs.good());
  21271. }
  21272. Server svr;
  21273. svr.set_mount_point("/static", ".");
  21274. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21275. svr.wait_until_ready();
  21276. Client cli(HOST, PORT);
  21277. // First request: get ETag
  21278. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21279. ASSERT_TRUE(res1);
  21280. ASSERT_EQ(200, res1->status);
  21281. ASSERT_TRUE(res1->has_header("ETag"));
  21282. std::string etag = res1->get_header_value("ETag");
  21283. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21284. // Since our server generates weak ETags (W/"..."), If-Range with our
  21285. // ETag should NOT result in partial content - it should return full content.
  21286. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21287. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21288. ASSERT_TRUE(res2);
  21289. // Weak ETag in If-Range -> full content (200), not partial (206)
  21290. EXPECT_EQ(200, res2->status);
  21291. EXPECT_EQ(content, res2->body);
  21292. EXPECT_FALSE(res2->has_header("Content-Range"));
  21293. // Range request with non-matching If-Range (ETag): should get 200 (full
  21294. // content)
  21295. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21296. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21297. ASSERT_TRUE(res3);
  21298. EXPECT_EQ(200, res3->status);
  21299. EXPECT_EQ(content, res3->body);
  21300. EXPECT_FALSE(res3->has_header("Content-Range"));
  21301. // Range request with strong ETag (hypothetical - our server doesn't generate
  21302. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21303. // should return full content)
  21304. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21305. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21306. ASSERT_TRUE(res4);
  21307. EXPECT_EQ(200, res4->status);
  21308. EXPECT_EQ(content, res4->body);
  21309. EXPECT_FALSE(res4->has_header("Content-Range"));
  21310. svr.stop();
  21311. t.join();
  21312. std::remove(fname);
  21313. }
  21314. TEST(ETagTest, IfRangeWithDate) {
  21315. using namespace httplib;
  21316. // Create a test file
  21317. const char *fname = "if_range_date_testfile.txt";
  21318. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21319. {
  21320. std::ofstream ofs(fname);
  21321. ofs << content;
  21322. ASSERT_TRUE(ofs.good());
  21323. }
  21324. Server svr;
  21325. svr.set_mount_point("/static", ".");
  21326. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21327. svr.wait_until_ready();
  21328. Client cli(HOST, PORT);
  21329. // First request: get Last-Modified
  21330. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21331. ASSERT_TRUE(res1);
  21332. ASSERT_EQ(200, res1->status);
  21333. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21334. std::string last_modified = res1->get_header_value("Last-Modified");
  21335. // Range request with matching If-Range (date): should get 206
  21336. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21337. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21338. ASSERT_TRUE(res2);
  21339. EXPECT_EQ(206, res2->status);
  21340. EXPECT_EQ("FGHIJ", res2->body);
  21341. // Range request with old If-Range date: should get 200 (full content)
  21342. Headers h3 = {{"Range", "bytes=5-9"},
  21343. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21344. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21345. ASSERT_TRUE(res3);
  21346. EXPECT_EQ(200, res3->status);
  21347. EXPECT_EQ(content, res3->body);
  21348. // Range request with future If-Range date: should get 206
  21349. Headers h4 = {{"Range", "bytes=0-4"},
  21350. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21351. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21352. ASSERT_TRUE(res4);
  21353. EXPECT_EQ(206, res4->status);
  21354. EXPECT_EQ("ABCDE", res4->body);
  21355. svr.stop();
  21356. t.join();
  21357. std::remove(fname);
  21358. }
  21359. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21360. using namespace httplib;
  21361. const char *fname = "etag_malformed.txt";
  21362. const char *content = "malformed-etag";
  21363. {
  21364. std::ofstream ofs(fname);
  21365. ofs << content;
  21366. ASSERT_TRUE(ofs.good());
  21367. }
  21368. Server svr;
  21369. svr.set_mount_point("/static", ".");
  21370. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21371. svr.wait_until_ready();
  21372. Client cli(HOST, PORT);
  21373. // baseline: should get 200 and an ETag
  21374. auto res1 = cli.Get("/static/etag_malformed.txt");
  21375. ASSERT_TRUE(res1);
  21376. ASSERT_EQ(200, res1->status);
  21377. ASSERT_TRUE(res1->has_header("ETag"));
  21378. // Malformed ETag value (missing quotes) should be treated as non-matching
  21379. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21380. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21381. ASSERT_TRUE(res_bad);
  21382. EXPECT_EQ(200, res_bad->status);
  21383. // Whitespace-only header value should be considered invalid / non-matching
  21384. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21385. "Host: localhost\r\n"
  21386. "If-None-Match: \r\n"
  21387. "Connection: close\r\n"
  21388. "\r\n";
  21389. std::string out;
  21390. ASSERT_TRUE(send_request(5, raw_req, &out));
  21391. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21392. svr.stop();
  21393. t.join();
  21394. std::remove(fname);
  21395. }
  21396. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21397. using namespace httplib;
  21398. const char *fname = "ims_invalid_format.txt";
  21399. const char *content = "ims-bad-format";
  21400. {
  21401. std::ofstream ofs(fname);
  21402. ofs << content;
  21403. ASSERT_TRUE(ofs.good());
  21404. }
  21405. Server svr;
  21406. svr.set_mount_point("/static", ".");
  21407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21408. svr.wait_until_ready();
  21409. Client cli(HOST, PORT);
  21410. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21411. ASSERT_TRUE(res1);
  21412. ASSERT_EQ(200, res1->status);
  21413. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21414. // If-Modified-Since with invalid format should not result in 304
  21415. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21416. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21417. ASSERT_TRUE(res_bad);
  21418. EXPECT_EQ(200, res_bad->status);
  21419. // If-Range with invalid date format should be treated as mismatch -> full
  21420. // content (200)
  21421. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21422. {"If-Range", "invalid-date"}};
  21423. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21424. ASSERT_TRUE(res_ifrange);
  21425. EXPECT_EQ(200, res_ifrange->status);
  21426. svr.stop();
  21427. t.join();
  21428. std::remove(fname);
  21429. }
  21430. TEST(ETagTest, IfRangeWithMalformedETag) {
  21431. using namespace httplib;
  21432. const char *fname = "ifrange_malformed.txt";
  21433. const std::string content = "0123456789";
  21434. {
  21435. std::ofstream ofs(fname);
  21436. ofs << content;
  21437. ASSERT_TRUE(ofs.good());
  21438. }
  21439. Server svr;
  21440. svr.set_mount_point("/static", ".");
  21441. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21442. svr.wait_until_ready();
  21443. Client cli(HOST, PORT);
  21444. // First request: get ETag
  21445. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21446. ASSERT_TRUE(res1);
  21447. ASSERT_EQ(200, res1->status);
  21448. ASSERT_TRUE(res1->has_header("ETag"));
  21449. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21450. // full content (200)
  21451. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21452. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21453. ASSERT_TRUE(res2);
  21454. EXPECT_EQ(200, res2->status);
  21455. EXPECT_EQ(content, res2->body);
  21456. svr.stop();
  21457. t.join();
  21458. std::remove(fname);
  21459. }
  21460. TEST(ETagTest, ExtremeLargeDateValues) {
  21461. using namespace httplib;
  21462. const char *fname = "ims_extreme_date.txt";
  21463. const char *content = "ims-extreme-date";
  21464. {
  21465. std::ofstream ofs(fname);
  21466. ofs << content;
  21467. ASSERT_TRUE(ofs.good());
  21468. }
  21469. Server svr;
  21470. svr.set_mount_point("/static", ".");
  21471. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21472. svr.wait_until_ready();
  21473. Client cli(HOST, PORT);
  21474. auto res1 = cli.Get(std::string("/static/") + fname);
  21475. ASSERT_TRUE(res1);
  21476. ASSERT_EQ(200, res1->status);
  21477. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21478. // Extremely large year that may overflow date parsing routines.
  21479. Headers h_large_date = {
  21480. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21481. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21482. ASSERT_TRUE(res_bad);
  21483. // Expect server to treat this as invalid/mismatch and return full content
  21484. EXPECT_EQ(200, res_bad->status);
  21485. // If-Range with extremely large date should be treated as mismatch -> full
  21486. // content (200)
  21487. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21488. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21489. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21490. ASSERT_TRUE(res_ifrange);
  21491. EXPECT_EQ(200, res_ifrange->status);
  21492. svr.stop();
  21493. t.join();
  21494. std::remove(fname);
  21495. }
  21496. TEST(ETagTest, NegativeFileModificationTime) {
  21497. using namespace httplib;
  21498. const char *fname = "ims_negative_mtime.txt";
  21499. const std::string content = "negative-mtime";
  21500. {
  21501. std::ofstream ofs(fname);
  21502. ofs << content;
  21503. ASSERT_TRUE(ofs.good());
  21504. }
  21505. // Try to set file mtime to a negative value. This may fail on some
  21506. // platforms/filesystems; if it fails, the test will still verify server
  21507. // behaves safely by performing a regular conditional request.
  21508. #if defined(__APPLE__) || defined(__linux__)
  21509. bool set_negative = false;
  21510. do {
  21511. struct timeval times[2];
  21512. // access time: now
  21513. times[0].tv_sec = time(nullptr);
  21514. times[0].tv_usec = 0;
  21515. // modification time: negative (e.g., -1)
  21516. times[1].tv_sec = -1;
  21517. times[1].tv_usec = 0;
  21518. if (utimes(fname, times) == 0) { set_negative = true; }
  21519. } while (0);
  21520. #else
  21521. bool set_negative = false;
  21522. #endif
  21523. Server svr;
  21524. svr.set_mount_point("/static", ".");
  21525. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21526. svr.wait_until_ready();
  21527. Client cli(HOST, PORT);
  21528. auto res1 = cli.Get(std::string("/static/") + fname);
  21529. ASSERT_TRUE(res1);
  21530. ASSERT_EQ(200, res1->status);
  21531. bool has_last_modified = res1->has_header("Last-Modified");
  21532. std::string last_modified;
  21533. if (has_last_modified) {
  21534. last_modified = res1->get_header_value("Last-Modified");
  21535. }
  21536. if (set_negative) {
  21537. // If we successfully set a negative mtime, ensure server returns a
  21538. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21539. // with an old date and ensure server handles it without crash.
  21540. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21541. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21542. ASSERT_TRUE(res2);
  21543. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21544. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21545. } else {
  21546. // Could not set negative mtime on this platform; fall back to verifying
  21547. // that normal invalid/malformed dates are treated safely (non-304).
  21548. Headers h_bad_date = {
  21549. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21550. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21551. ASSERT_TRUE(res_bad);
  21552. EXPECT_EQ(200, res_bad->status);
  21553. }
  21554. svr.stop();
  21555. t.join();
  21556. std::remove(fname);
  21557. }
  21558. //==============================================================================
  21559. // Integration Tests with Server
  21560. //==============================================================================
  21561. class SSEIntegrationTest : public ::testing::Test {
  21562. protected:
  21563. void SetUp() override {
  21564. stop_server_.store(false);
  21565. events_.clear();
  21566. server_ = httplib::detail::make_unique<Server>();
  21567. setup_server();
  21568. start_server();
  21569. }
  21570. void TearDown() override {
  21571. stop_server_.store(true);
  21572. event_cv_.notify_all();
  21573. server_->stop();
  21574. if (server_thread_.joinable()) { server_thread_.join(); }
  21575. }
  21576. void setup_server() {
  21577. // Simple SSE endpoint
  21578. server_->Get("/events", [this](const Request &req, Response &res) {
  21579. auto last_id = req.get_header_value("Last-Event-ID");
  21580. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21581. res.set_chunked_content_provider(
  21582. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21583. std::unique_lock<std::mutex> lock(event_mutex_);
  21584. if (event_cv_.wait_for(
  21585. lock, std::chrono::milliseconds(200), [this] {
  21586. return !events_.empty() || stop_server_.load();
  21587. })) {
  21588. if (stop_server_.load()) { return false; }
  21589. if (!events_.empty()) {
  21590. std::string event = events_.front();
  21591. events_.erase(events_.begin());
  21592. sink.write(event.data(), event.size());
  21593. return true;
  21594. }
  21595. }
  21596. return !stop_server_.load();
  21597. });
  21598. });
  21599. // Endpoint that returns error
  21600. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21601. res.status = 500;
  21602. res.set_content("Internal Server Error", "text/plain");
  21603. });
  21604. // Endpoint for custom event types
  21605. server_->Get("/custom-events", [](const Request &, Response &res) {
  21606. res.set_chunked_content_provider(
  21607. "text/event-stream", [](size_t offset, DataSink &sink) {
  21608. if (offset == 0) {
  21609. std::string event = "event: update\ndata: updated\n\n"
  21610. "event: delete\ndata: deleted\n\n";
  21611. sink.write(event.data(), event.size());
  21612. }
  21613. return false; // End stream after sending
  21614. });
  21615. });
  21616. }
  21617. void start_server() {
  21618. port_ = server_->bind_to_any_port(HOST);
  21619. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21620. // Wait for server to start
  21621. while (!server_->is_running()) {
  21622. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21623. }
  21624. }
  21625. int get_port() const { return port_; }
  21626. void send_event(const std::string &event) {
  21627. std::lock_guard<std::mutex> lock(event_mutex_);
  21628. events_.push_back(event);
  21629. event_cv_.notify_all();
  21630. }
  21631. std::unique_ptr<Server> server_;
  21632. std::thread server_thread_;
  21633. std::mutex event_mutex_;
  21634. std::condition_variable event_cv_;
  21635. std::vector<std::string> events_;
  21636. std::atomic<bool> stop_server_{false};
  21637. std::string last_received_event_id_;
  21638. int port_ = 0;
  21639. };
  21640. //==============================================================================
  21641. // SSE Parsing Tests
  21642. //==============================================================================
  21643. class SSEParsingTest : public SSEIntegrationTest {
  21644. protected:
  21645. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21646. // A trailing sentinel event tells when the whole stream has been parsed.
  21647. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21648. auto body = stream + "event: end\ndata: end\n\n";
  21649. server_->Get("/parse", [body](const Request &, Response &res) {
  21650. res.set_content(body, "text/event-stream");
  21651. });
  21652. return collect("/parse");
  21653. }
  21654. // Runs SSEClient against path until an "end" event arrives and returns the
  21655. // messages dispatched before it
  21656. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21657. Client client(HOST, get_port());
  21658. sse::SSEClient sse(client, path);
  21659. std::mutex mutex;
  21660. std::condition_variable cv;
  21661. std::vector<sse::SSEMessage> messages;
  21662. auto done = false;
  21663. sse.on_message([&](const sse::SSEMessage &msg) {
  21664. std::lock_guard<std::mutex> lock(mutex);
  21665. // Ignore a replay from a reconnect that races with stop()
  21666. if (!done) { messages.push_back(msg); }
  21667. });
  21668. sse.on_event("end", [&](const sse::SSEMessage &) {
  21669. std::lock_guard<std::mutex> lock(mutex);
  21670. done = true;
  21671. cv.notify_all();
  21672. });
  21673. sse.set_reconnect_interval(100);
  21674. sse.start_async();
  21675. {
  21676. std::unique_lock<std::mutex> lock(mutex);
  21677. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21678. }
  21679. sse.stop();
  21680. EXPECT_TRUE(done);
  21681. return messages;
  21682. }
  21683. };
  21684. TEST_F(SSEParsingTest, SingleLineData) {
  21685. auto msgs = parse("data: hello\n\n");
  21686. ASSERT_EQ(msgs.size(), 1u);
  21687. EXPECT_EQ(msgs[0].data, "hello");
  21688. EXPECT_EQ(msgs[0].event, "message");
  21689. }
  21690. TEST_F(SSEParsingTest, MultiLineData) {
  21691. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21692. ASSERT_EQ(msgs.size(), 1u);
  21693. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21694. }
  21695. TEST_F(SSEParsingTest, CustomEventType) {
  21696. auto msgs = parse("event: update\ndata: payload\n\n");
  21697. ASSERT_EQ(msgs.size(), 1u);
  21698. EXPECT_EQ(msgs[0].event, "update");
  21699. EXPECT_EQ(msgs[0].data, "payload");
  21700. }
  21701. TEST_F(SSEParsingTest, EventIdHandling) {
  21702. auto msgs = parse("id: 12345\ndata: test\n\n");
  21703. ASSERT_EQ(msgs.size(), 1u);
  21704. EXPECT_EQ(msgs[0].id, "12345");
  21705. }
  21706. TEST_F(SSEParsingTest, EmptyEventId) {
  21707. auto msgs = parse("id:\ndata: test\n\n");
  21708. ASSERT_EQ(msgs.size(), 1u);
  21709. EXPECT_EQ(msgs[0].id, "");
  21710. }
  21711. TEST_F(SSEParsingTest, CommentsIgnored) {
  21712. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21713. ASSERT_EQ(msgs.size(), 1u);
  21714. EXPECT_EQ(msgs[0].data, "hello");
  21715. EXPECT_EQ(msgs[0].event, "message");
  21716. }
  21717. TEST_F(SSEParsingTest, ColonInValue) {
  21718. auto msgs = parse("data: hello:world:test\n\n");
  21719. ASSERT_EQ(msgs.size(), 1u);
  21720. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21721. }
  21722. TEST_F(SSEParsingTest, FieldNameOnly) {
  21723. // A line without a colon is a field name with an empty value
  21724. auto msgs = parse("data\n\n");
  21725. ASSERT_EQ(msgs.size(), 1u);
  21726. EXPECT_EQ(msgs[0].data, "");
  21727. }
  21728. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21729. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21730. ASSERT_EQ(msgs.size(), 1u);
  21731. EXPECT_EQ(msgs[0].event, "update");
  21732. EXPECT_EQ(msgs[0].data, "hello");
  21733. }
  21734. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21735. auto msgs = parse("data\r\n\r\n");
  21736. ASSERT_EQ(msgs.size(), 1u);
  21737. EXPECT_EQ(msgs[0].data, "");
  21738. }
  21739. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21740. auto msgs = parse("event: update\rdata: hello\r\r");
  21741. ASSERT_EQ(msgs.size(), 1u);
  21742. EXPECT_EQ(msgs[0].event, "update");
  21743. EXPECT_EQ(msgs[0].data, "hello");
  21744. }
  21745. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21746. // Chunk boundaries fall inside every \r\n and right before the first one
  21747. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21748. "\n\r", "\nevent: end\ndata: end\n\n"};
  21749. server_->Get("/split", [chunks](const Request &, Response &res) {
  21750. auto i = std::make_shared<size_t>(0);
  21751. res.set_chunked_content_provider(
  21752. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21753. if (*i == chunks.size()) {
  21754. sink.done();
  21755. } else {
  21756. sink.write(chunks[*i].data(), chunks[*i].size());
  21757. (*i)++;
  21758. }
  21759. return true;
  21760. });
  21761. });
  21762. auto msgs = collect("/split");
  21763. ASSERT_EQ(msgs.size(), 1u);
  21764. EXPECT_EQ(msgs[0].event, "update");
  21765. EXPECT_EQ(msgs[0].data, "hello");
  21766. }
  21767. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21768. // Only a BOM at the start of the stream is ignored
  21769. auto msgs = parse("\xEF\xBB\xBF"
  21770. "data: first\n\n"
  21771. "\xEF\xBB\xBF"
  21772. "data: second\n\n");
  21773. ASSERT_EQ(msgs.size(), 1u);
  21774. EXPECT_EQ(msgs[0].data, "first");
  21775. }
  21776. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21777. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21778. ASSERT_EQ(msgs.size(), 1u);
  21779. EXPECT_EQ(msgs[0].data, "hello");
  21780. EXPECT_EQ(msgs[0].event, "message");
  21781. }
  21782. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21783. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21784. ASSERT_EQ(msgs.size(), 2u);
  21785. EXPECT_EQ(msgs[0].data, "hello");
  21786. EXPECT_EQ(msgs[1].data, "hello");
  21787. }
  21788. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21789. // An event without data is not dispatched, and its type must not leak
  21790. // into the next event
  21791. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21792. ASSERT_EQ(msgs.size(), 1u);
  21793. EXPECT_EQ(msgs[0].event, "message");
  21794. EXPECT_EQ(msgs[0].data, "hello");
  21795. }
  21796. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21797. // Also when the empty field replaces an earlier type
  21798. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21799. ASSERT_EQ(msgs.size(), 2u);
  21800. EXPECT_EQ(msgs[0].event, "message");
  21801. EXPECT_EQ(msgs[1].event, "message");
  21802. }
  21803. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21804. // The first connection sends only an id; the second echoes back the
  21805. // Last-Event-ID it was reconnected with
  21806. std::atomic<int> connection_count{0};
  21807. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21808. if (connection_count++ == 0) {
  21809. res.set_content("id: 42\n\n", "text/event-stream");
  21810. } else {
  21811. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21812. "\n\nevent: end\ndata: end\n\n",
  21813. "text/event-stream");
  21814. }
  21815. });
  21816. auto msgs = collect("/id-only");
  21817. ASSERT_EQ(msgs.size(), 1u);
  21818. EXPECT_EQ(msgs[0].data, "42");
  21819. }
  21820. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21821. // The first connection sets an id and then clears it with an empty one; the
  21822. // second reports whether it was reconnected with a Last-Event-ID
  21823. std::atomic<int> connection_count{0};
  21824. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21825. if (connection_count++ == 0) {
  21826. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21827. "text/event-stream");
  21828. } else {
  21829. res.set_content(
  21830. std::string("data: ") +
  21831. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21832. "\n\nevent: end\ndata: end\n\n",
  21833. "text/event-stream");
  21834. }
  21835. });
  21836. auto msgs = collect("/id-clear");
  21837. ASSERT_EQ(msgs.size(), 3u);
  21838. EXPECT_EQ(msgs[0].id, "1");
  21839. EXPECT_EQ(msgs[1].id, "");
  21840. EXPECT_EQ(msgs[2].data, "not sent");
  21841. }
  21842. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21843. // The first connection sets an id and then sends ids that cannot be carried
  21844. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21845. // with
  21846. std::atomic<int> connection_count{0};
  21847. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21848. if (connection_count++ == 0) {
  21849. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21850. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21851. "text/event-stream");
  21852. } else {
  21853. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21854. "\n\nevent: end\ndata: end\n\n",
  21855. "text/event-stream");
  21856. }
  21857. });
  21858. auto msgs = collect("/id-unsendable");
  21859. ASSERT_EQ(msgs.size(), 1u);
  21860. EXPECT_EQ(msgs[0].data, "42");
  21861. }
  21862. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21863. auto msgs = parse("event: notification\nid: evt-42\n"
  21864. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21865. ASSERT_EQ(msgs.size(), 1u);
  21866. EXPECT_EQ(msgs[0].event, "notification");
  21867. EXPECT_EQ(msgs[0].id, "evt-42");
  21868. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21869. }
  21870. TEST(SSEMessageTest, Clear) {
  21871. sse::SSEMessage msg;
  21872. msg.event = "custom";
  21873. msg.data = "some data";
  21874. msg.id = "123";
  21875. msg.clear();
  21876. EXPECT_EQ(msg.event, "message");
  21877. EXPECT_EQ(msg.data, "");
  21878. EXPECT_EQ(msg.id, "");
  21879. }
  21880. //==============================================================================
  21881. // SSE Integration Tests
  21882. //==============================================================================
  21883. // Test: Successful connection and on_open callback
  21884. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21885. // Add a simple endpoint that sends one event and closes
  21886. server_->Get("/simple-event", [](const Request &, Response &res) {
  21887. res.set_chunked_content_provider(
  21888. "text/event-stream", [](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. return false; // Close stream after sending
  21894. });
  21895. });
  21896. Client client("localhost", get_port());
  21897. sse::SSEClient sse(client, "/simple-event");
  21898. std::atomic<bool> open_called{false};
  21899. std::atomic<bool> message_received{false};
  21900. sse.on_open([&open_called]() { open_called.store(true); });
  21901. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21902. if (msg.data == "hello") { message_received.store(true); }
  21903. });
  21904. sse.set_reconnect_interval(100);
  21905. sse.set_max_reconnect_attempts(1);
  21906. // Start async
  21907. sse.start_async();
  21908. // Wait for message to be processed
  21909. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21910. sse.stop();
  21911. EXPECT_TRUE(open_called.load());
  21912. EXPECT_TRUE(message_received.load());
  21913. }
  21914. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21915. // A data line that never ends.
  21916. server_->Get("/endless-line", [](const Request &, Response &res) {
  21917. res.set_chunked_content_provider(
  21918. "text/event-stream", [](size_t offset, DataSink &sink) {
  21919. if (offset == 0) { sink.write("data: ", 6); }
  21920. std::string chunk(64 * 1024, 'A');
  21921. return sink.write(chunk.data(), chunk.size());
  21922. });
  21923. });
  21924. Client client("localhost", get_port());
  21925. sse::SSEClient sse(client, "/endless-line");
  21926. std::atomic<bool> too_long{false};
  21927. sse.on_error([&](Error err) {
  21928. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21929. });
  21930. sse.set_max_reconnect_attempts(1);
  21931. sse.start_async();
  21932. for (int i = 0; i < 500 && !too_long; i++) {
  21933. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21934. }
  21935. sse.stop();
  21936. EXPECT_TRUE(too_long);
  21937. }
  21938. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21939. // Far more in all than the client's payload limit below.
  21940. server_->Get("/many-events", [](const Request &, Response &res) {
  21941. res.set_chunked_content_provider(
  21942. "text/event-stream", [](size_t offset, DataSink &sink) {
  21943. if (offset == 0) {
  21944. std::string events;
  21945. for (int i = 0; i < 1000; i++) {
  21946. events += "data: message\n\n";
  21947. }
  21948. sink.write(events.data(), events.size());
  21949. }
  21950. return false;
  21951. });
  21952. });
  21953. Client client("localhost", get_port());
  21954. client.set_payload_max_length(1024);
  21955. sse::SSEClient sse(client, "/many-events");
  21956. std::atomic<int> messages{0};
  21957. std::atomic<bool> too_large{false};
  21958. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21959. sse.on_error([&](Error err) {
  21960. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21961. });
  21962. sse.set_max_reconnect_attempts(1);
  21963. sse.start_async();
  21964. for (int i = 0; i < 500 && messages < 1000; i++) {
  21965. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21966. }
  21967. sse.stop();
  21968. EXPECT_GE(messages.load(), 1000);
  21969. EXPECT_FALSE(too_large);
  21970. }
  21971. // Test: on_message callback
  21972. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21973. // Endpoint that sends multiple events then closes
  21974. server_->Get("/multi-event", [](const Request &, Response &res) {
  21975. res.set_chunked_content_provider(
  21976. "text/event-stream", [](size_t offset, DataSink &sink) {
  21977. if (offset == 0) {
  21978. std::string events = "data: message1\n\ndata: message2\n\n";
  21979. sink.write(events.data(), events.size());
  21980. }
  21981. return false;
  21982. });
  21983. });
  21984. Client client("localhost", get_port());
  21985. sse::SSEClient sse(client, "/multi-event");
  21986. std::vector<std::string> received_messages;
  21987. std::mutex messages_mutex;
  21988. sse.on_message([&](const sse::SSEMessage &msg) {
  21989. std::lock_guard<std::mutex> lock(messages_mutex);
  21990. received_messages.push_back(msg.data);
  21991. });
  21992. sse.set_reconnect_interval(100);
  21993. sse.set_max_reconnect_attempts(1);
  21994. sse.start_async();
  21995. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21996. sse.stop();
  21997. std::lock_guard<std::mutex> lock(messages_mutex);
  21998. EXPECT_GE(received_messages.size(), 2u);
  21999. if (received_messages.size() >= 2) {
  22000. EXPECT_EQ(received_messages[0], "message1");
  22001. EXPECT_EQ(received_messages[1], "message2");
  22002. }
  22003. }
  22004. // Test: on_event for specific types
  22005. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22006. Client client("localhost", get_port());
  22007. sse::SSEClient sse(client, "/custom-events");
  22008. std::atomic<bool> update_received{false};
  22009. std::atomic<bool> delete_received{false};
  22010. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22011. if (msg.data == "updated") { update_received.store(true); }
  22012. });
  22013. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22014. if (msg.data == "deleted") { delete_received.store(true); }
  22015. });
  22016. sse.set_max_reconnect_attempts(1);
  22017. sse.start_async();
  22018. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22019. sse.stop();
  22020. EXPECT_TRUE(update_received.load());
  22021. EXPECT_TRUE(delete_received.load());
  22022. }
  22023. // Test: on_error callback on connection failure
  22024. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22025. // Connect to a non-existent port
  22026. Client client("localhost", 59999);
  22027. sse::SSEClient sse(client, "/events");
  22028. std::atomic<bool> error_called{false};
  22029. Error received_error = Error::Success;
  22030. sse.on_error([&](Error err) {
  22031. error_called.store(true);
  22032. received_error = err;
  22033. });
  22034. sse.set_reconnect_interval(50);
  22035. sse.set_max_reconnect_attempts(1);
  22036. sse.start_async();
  22037. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22038. sse.stop();
  22039. EXPECT_TRUE(error_called.load());
  22040. EXPECT_NE(received_error, Error::Success);
  22041. }
  22042. // Test: Last-Event-ID header sent on reconnect
  22043. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22044. // Endpoint that sends event with ID
  22045. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22046. res.set_chunked_content_provider(
  22047. "text/event-stream", [](size_t offset, DataSink &sink) {
  22048. if (offset == 0) {
  22049. std::string event = "id: evt-123\ndata: test\n\n";
  22050. sink.write(event.data(), event.size());
  22051. }
  22052. return false;
  22053. });
  22054. });
  22055. Client client("localhost", get_port());
  22056. sse::SSEClient sse(client, "/event-with-id");
  22057. std::atomic<bool> id_received{false};
  22058. sse.on_message([&](const sse::SSEMessage &msg) {
  22059. if (!msg.id.empty()) { id_received.store(true); }
  22060. });
  22061. sse.set_reconnect_interval(100);
  22062. sse.set_max_reconnect_attempts(1);
  22063. sse.start_async();
  22064. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22065. sse.stop();
  22066. EXPECT_TRUE(id_received.load());
  22067. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22068. }
  22069. // Test: Manual stop
  22070. TEST_F(SSEIntegrationTest, ManualStop) {
  22071. // Endpoint that sends one event and stays open briefly. The server outlives
  22072. // this test body, so the provider uses the fixture's flag, not a local.
  22073. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22074. res.set_chunked_content_provider(
  22075. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22076. if (offset == 0) {
  22077. std::string event = "data: connected\n\n";
  22078. sink.write(event.data(), event.size());
  22079. }
  22080. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22081. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22082. }
  22083. return false;
  22084. });
  22085. });
  22086. Client client("localhost", get_port());
  22087. sse::SSEClient sse(client, "/stay-open");
  22088. std::atomic<bool> connected{false};
  22089. sse.on_open([&connected]() { connected.store(true); });
  22090. sse.set_reconnect_interval(100);
  22091. sse.set_max_reconnect_attempts(1);
  22092. sse.start_async();
  22093. // Wait for connection to establish
  22094. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22095. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22096. }
  22097. EXPECT_TRUE(connected.load());
  22098. EXPECT_TRUE(sse.is_connected());
  22099. // Signal handler to stop
  22100. stop_server_.store(true);
  22101. // Stop SSE client
  22102. sse.stop();
  22103. EXPECT_FALSE(sse.is_connected());
  22104. }
  22105. // Sends one event, then nothing until stop is set
  22106. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22107. return [&stop](const Request &, Response &res) {
  22108. res.set_chunked_content_provider(
  22109. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22110. if (offset == 0) {
  22111. std::string event = "data: hello\n\n";
  22112. sink.write(event.data(), event.size());
  22113. }
  22114. while (!stop.load()) {
  22115. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22116. }
  22117. return false;
  22118. });
  22119. };
  22120. }
  22121. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22122. static void check_stop_interrupts_blocked_read(Client &client) {
  22123. client.set_read_timeout(30, 0);
  22124. for (auto by_destructor : {false, true}) {
  22125. std::atomic<bool> received{false};
  22126. std::chrono::steady_clock::time_point start;
  22127. {
  22128. sse::SSEClient sse(client, "/idle-stream");
  22129. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22130. sse.start_async();
  22131. for (int i = 0; i < 500 && !received.load(); ++i) {
  22132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22133. }
  22134. ASSERT_TRUE(received.load());
  22135. // Let the client block in the next read
  22136. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22137. start = std::chrono::steady_clock::now();
  22138. if (!by_destructor) { sse.stop(); }
  22139. }
  22140. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22141. std::chrono::seconds(2));
  22142. }
  22143. }
  22144. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22145. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22146. Client client("localhost", get_port());
  22147. check_stop_interrupts_blocked_read(client);
  22148. }
  22149. #ifdef CPPHTTPLIB_SSL_ENABLED
  22150. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22152. std::atomic<bool> done{false};
  22153. svr.Get("/idle-stream", idle_event_stream(done));
  22154. auto port = svr.bind_to_any_port(HOST);
  22155. std::thread t([&] { svr.listen_after_bind(); });
  22156. auto se = detail::scope_exit([&] {
  22157. done.store(true);
  22158. svr.stop();
  22159. t.join();
  22160. });
  22161. svr.wait_until_ready();
  22162. Client client("https://localhost:" + std::to_string(port));
  22163. client.enable_server_certificate_verification(false);
  22164. check_stop_interrupts_blocked_read(client);
  22165. }
  22166. #endif
  22167. // Test: SSEClient with custom headers
  22168. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22169. // Setup a server endpoint that checks for custom header
  22170. std::atomic<bool> header_received{false};
  22171. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22172. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22173. header_received.store(true);
  22174. }
  22175. res.set_chunked_content_provider("text/event-stream",
  22176. [](size_t, DataSink &) { return false; });
  22177. });
  22178. Client client("localhost", get_port());
  22179. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22180. sse::SSEClient sse(client, "/header-check", headers);
  22181. sse.set_max_reconnect_attempts(1);
  22182. sse.start_async();
  22183. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22184. sse.stop();
  22185. EXPECT_TRUE(header_received.load());
  22186. }
  22187. // Test: Reconnect interval configuration
  22188. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22189. Client client("localhost", get_port());
  22190. sse::SSEClient sse(client, "/events");
  22191. auto &result = sse.set_reconnect_interval(500);
  22192. // Builder pattern should return reference to self
  22193. EXPECT_EQ(&result, &sse);
  22194. }
  22195. // Test: Max reconnect attempts
  22196. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22197. // Connect to non-existent port to force reconnects
  22198. Client client("localhost", 59998);
  22199. sse::SSEClient sse(client, "/events");
  22200. std::atomic<int> error_count{0};
  22201. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22202. sse.set_reconnect_interval(50);
  22203. sse.set_max_reconnect_attempts(2);
  22204. auto start = std::chrono::steady_clock::now();
  22205. sse.start(); // Blocking call
  22206. auto end = std::chrono::steady_clock::now();
  22207. // Should have stopped after 2 failed attempts
  22208. EXPECT_GE(error_count.load(), 2);
  22209. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22210. auto duration =
  22211. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22212. #ifdef _WIN32
  22213. // Windows is much slower for socket connection failures
  22214. EXPECT_LT(duration.count(), 7000);
  22215. #else
  22216. EXPECT_LT(duration.count(), 1000);
  22217. #endif
  22218. }
  22219. // Test: Multi-line data in integration
  22220. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22221. // Endpoint with multi-line data
  22222. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22223. res.set_chunked_content_provider(
  22224. "text/event-stream", [](size_t offset, DataSink &sink) {
  22225. if (offset == 0) {
  22226. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22227. sink.write(event.data(), event.size());
  22228. }
  22229. return false;
  22230. });
  22231. });
  22232. Client client("localhost", get_port());
  22233. sse::SSEClient sse(client, "/multiline-data");
  22234. std::string received_data;
  22235. std::mutex data_mutex;
  22236. sse.on_message([&](const sse::SSEMessage &msg) {
  22237. std::lock_guard<std::mutex> lock(data_mutex);
  22238. received_data = msg.data;
  22239. });
  22240. sse.set_reconnect_interval(100);
  22241. sse.set_max_reconnect_attempts(1);
  22242. sse.start_async();
  22243. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22244. sse.stop();
  22245. std::lock_guard<std::mutex> lock(data_mutex);
  22246. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22247. }
  22248. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22249. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22250. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22251. DataSink &sink) {
  22252. if (offset == 0) {
  22253. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22254. sink.write(events.data(), events.size());
  22255. }
  22256. return false;
  22257. });
  22258. });
  22259. Client client("localhost", get_port());
  22260. sse::SSEClient sse(client, "/empty-data-lines");
  22261. std::mutex mutex;
  22262. std::condition_variable cv;
  22263. std::vector<std::string> received;
  22264. sse.on_message([&](const sse::SSEMessage &msg) {
  22265. std::lock_guard<std::mutex> lock(mutex);
  22266. received.push_back(msg.data);
  22267. cv.notify_all();
  22268. });
  22269. sse.set_max_reconnect_attempts(1);
  22270. sse.start_async();
  22271. {
  22272. std::unique_lock<std::mutex> lock(mutex);
  22273. cv.wait_for(lock, std::chrono::seconds(2),
  22274. [&] { return received.size() >= 3; });
  22275. }
  22276. sse.stop();
  22277. ASSERT_GE(received.size(), 3u);
  22278. EXPECT_EQ(received[0], "");
  22279. EXPECT_EQ(received[1], "\nhello");
  22280. EXPECT_EQ(received[2], "");
  22281. }
  22282. // Test: Auto-reconnect after server disconnection
  22283. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22284. std::atomic<int> connection_count{0};
  22285. std::atomic<int> message_count{0};
  22286. // Endpoint that sends one event and closes, forcing reconnect
  22287. server_->Get("/reconnect-test",
  22288. [&connection_count](const Request &, Response &res) {
  22289. connection_count.fetch_add(1);
  22290. res.set_chunked_content_provider(
  22291. "text/event-stream", [](size_t offset, DataSink &sink) {
  22292. if (offset == 0) {
  22293. std::string event = "data: hello\n\n";
  22294. sink.write(event.data(), event.size());
  22295. }
  22296. return false; // Close connection after sending
  22297. });
  22298. });
  22299. Client client("localhost", get_port());
  22300. sse::SSEClient sse(client, "/reconnect-test");
  22301. sse.on_message([&message_count](const sse::SSEMessage &) {
  22302. message_count.fetch_add(1);
  22303. });
  22304. sse.set_reconnect_interval(100);
  22305. sse.set_max_reconnect_attempts(3);
  22306. sse.start_async();
  22307. // Wait long enough for multiple reconnects
  22308. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22309. sse.stop();
  22310. // Should have connected multiple times (initial + reconnects)
  22311. EXPECT_GE(connection_count.load(), 2);
  22312. // Should have received messages from multiple connections
  22313. EXPECT_GE(message_count.load(), 2);
  22314. }
  22315. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22316. std::atomic<int> connection_count{0};
  22317. // Neither Content-Length nor chunked: the close ends the stream
  22318. server_->Get("/close-delimited",
  22319. [&connection_count](const Request &, Response &res) {
  22320. connection_count.fetch_add(1);
  22321. res.set_content_provider(
  22322. "text/event-stream", [](size_t offset, DataSink &sink) {
  22323. if (offset == 0) {
  22324. std::string event = "data: hello\n\n";
  22325. sink.write(event.data(), event.size());
  22326. } else {
  22327. sink.done();
  22328. }
  22329. return true;
  22330. });
  22331. });
  22332. Client client("localhost", get_port());
  22333. sse::SSEClient sse(client, "/close-delimited");
  22334. std::atomic<int> error_count{0};
  22335. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22336. sse.set_reconnect_interval(100);
  22337. sse.start_async();
  22338. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22340. }
  22341. sse.stop();
  22342. // Reconnects as after any end of the stream, but reports no error
  22343. EXPECT_GE(connection_count.load(), 2);
  22344. EXPECT_EQ(0, error_count.load());
  22345. }
  22346. // Test: A retry field that is not all ASCII digits is ignored
  22347. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22348. std::atomic<int> connection_count{0};
  22349. server_->Get("/bad-retry",
  22350. [&connection_count](const Request &, Response &res) {
  22351. connection_count.fetch_add(1);
  22352. res.set_chunked_content_provider(
  22353. "text/event-stream", [](size_t offset, DataSink &sink) {
  22354. if (offset == 0) {
  22355. std::string event = "retry: -1\ndata: hello\n\n";
  22356. sink.write(event.data(), event.size());
  22357. }
  22358. return false;
  22359. });
  22360. });
  22361. Client client("localhost", get_port());
  22362. sse::SSEClient sse(client, "/bad-retry");
  22363. sse.set_reconnect_interval(10000);
  22364. sse.start_async();
  22365. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22366. sse.stop();
  22367. EXPECT_EQ(connection_count.load(), 1);
  22368. }
  22369. // Test: A retry field of all ASCII digits sets the reconnection time
  22370. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22371. std::mutex mutex;
  22372. std::condition_variable cv;
  22373. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22374. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22375. {
  22376. std::lock_guard<std::mutex> lock(mutex);
  22377. connected_at.push_back(std::chrono::steady_clock::now());
  22378. cv.notify_all();
  22379. }
  22380. res.set_chunked_content_provider(
  22381. "text/event-stream", [](size_t offset, DataSink &sink) {
  22382. if (offset == 0) {
  22383. std::string event = "retry: 0\ndata: hello\n\n";
  22384. sink.write(event.data(), event.size());
  22385. }
  22386. return false;
  22387. });
  22388. });
  22389. Client client("localhost", get_port());
  22390. sse::SSEClient sse(client, "/zero-retry");
  22391. sse.set_reconnect_interval(10000);
  22392. sse.start_async();
  22393. {
  22394. std::unique_lock<std::mutex> lock(mutex);
  22395. cv.wait_for(lock, std::chrono::seconds(5),
  22396. [&] { return connected_at.size() >= 2; });
  22397. }
  22398. sse.stop();
  22399. // The server-supplied interval is applied, but never below 100ms, so
  22400. // "retry: 0" does not cause a busy reconnect loop
  22401. std::lock_guard<std::mutex> lock(mutex);
  22402. ASSERT_GE(connected_at.size(), 2u);
  22403. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22404. connected_at[1] - connected_at[0])
  22405. .count();
  22406. EXPECT_GE(interval_ms, 100);
  22407. }
  22408. // Test: Last-Event-ID sent on reconnect
  22409. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22410. std::atomic<int> connection_count{0};
  22411. std::vector<std::string> received_last_event_ids;
  22412. std::mutex id_mutex;
  22413. // Endpoint that checks Last-Event-ID header and sends event with ID
  22414. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22415. int conn = connection_count.fetch_add(1);
  22416. // Capture the Last-Event-ID header from each connection
  22417. {
  22418. std::lock_guard<std::mutex> lock(id_mutex);
  22419. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22420. }
  22421. res.set_chunked_content_provider(
  22422. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22423. if (offset == 0) {
  22424. std::string event =
  22425. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22426. sink.write(event.data(), event.size());
  22427. }
  22428. return false;
  22429. });
  22430. });
  22431. Client client("localhost", get_port());
  22432. sse::SSEClient sse(client, "/reconnect-with-id");
  22433. sse.set_reconnect_interval(100);
  22434. sse.set_max_reconnect_attempts(3);
  22435. sse.start_async();
  22436. // Wait for at least 2 connections
  22437. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22438. sse.stop();
  22439. // Verify behavior
  22440. std::lock_guard<std::mutex> lock(id_mutex);
  22441. EXPECT_GE(received_last_event_ids.size(), 2u);
  22442. // First connection should have no Last-Event-ID
  22443. if (!received_last_event_ids.empty()) {
  22444. EXPECT_EQ(received_last_event_ids[0], "");
  22445. }
  22446. // Second connection should have Last-Event-ID from first connection
  22447. if (received_last_event_ids.size() >= 2) {
  22448. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22449. }
  22450. }
  22451. // Test: set_headers updates headers used on reconnect
  22452. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22453. std::vector<std::string> received_tokens;
  22454. std::mutex token_mutex;
  22455. // Endpoint that captures Authorization header
  22456. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22457. {
  22458. std::lock_guard<std::mutex> lock(token_mutex);
  22459. received_tokens.push_back(req.get_header_value("Authorization"));
  22460. }
  22461. res.set_chunked_content_provider(
  22462. "text/event-stream", [](size_t offset, DataSink &sink) {
  22463. if (offset == 0) {
  22464. std::string event = "data: hello\n\n";
  22465. sink.write(event.data(), event.size());
  22466. }
  22467. return false; // Close connection to trigger reconnect
  22468. });
  22469. });
  22470. Client client("localhost", get_port());
  22471. Headers headers = {{"Authorization", "Bearer old-token"}};
  22472. sse::SSEClient sse(client, "/auth-check", headers);
  22473. // Update headers on each successful connection
  22474. sse.on_open(
  22475. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22476. sse.set_reconnect_interval(100);
  22477. sse.set_max_reconnect_attempts(3);
  22478. sse.start_async();
  22479. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22480. sse.stop();
  22481. std::lock_guard<std::mutex> lock(token_mutex);
  22482. ASSERT_GE(received_tokens.size(), 2u);
  22483. // First connection uses original header
  22484. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22485. // Second connection uses updated header from set_headers
  22486. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22487. }
  22488. // Test: 401 allows reconnection (so on_error can refresh headers)
  22489. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22490. std::atomic<int> connection_count{0};
  22491. // Endpoint: returns 401 on first attempt, 200 on second
  22492. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22493. int conn = connection_count.fetch_add(1);
  22494. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22495. res.status = StatusCode::Unauthorized_401;
  22496. res.set_content("Unauthorized", "text/plain");
  22497. return;
  22498. }
  22499. res.set_chunked_content_provider(
  22500. "text/event-stream", [](size_t offset, DataSink &sink) {
  22501. if (offset == 0) {
  22502. std::string event = "data: authenticated\n\n";
  22503. sink.write(event.data(), event.size());
  22504. }
  22505. return false;
  22506. });
  22507. });
  22508. Client client("localhost", get_port());
  22509. Headers headers = {{"Authorization", "Bearer expired"}};
  22510. sse::SSEClient sse(client, "/auth-retry", headers);
  22511. std::atomic<bool> message_received{false};
  22512. // Refresh token on error
  22513. sse.on_error(
  22514. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22515. sse.on_message([&](const sse::SSEMessage &msg) {
  22516. if (msg.data == "authenticated") { message_received.store(true); }
  22517. });
  22518. sse.set_reconnect_interval(100);
  22519. sse.set_max_reconnect_attempts(3);
  22520. sse.start_async();
  22521. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22522. sse.stop();
  22523. // Should have reconnected after 401 and succeeded with new token
  22524. EXPECT_GE(connection_count.load(), 2);
  22525. EXPECT_TRUE(message_received.load());
  22526. }
  22527. TEST(Issue2318Test, EmptyHostString) {
  22528. {
  22529. httplib::Client cli_empty("", PORT);
  22530. auto res = cli_empty.Get("/");
  22531. ASSERT_FALSE(res);
  22532. EXPECT_EQ(httplib::Error::Connection, res.error());
  22533. }
  22534. {
  22535. httplib::Client cli(" ", PORT);
  22536. auto res = cli.Get("/");
  22537. ASSERT_FALSE(res);
  22538. EXPECT_EQ(httplib::Error::Connection, res.error());
  22539. }
  22540. }
  22541. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22542. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22543. Server svr;
  22544. // Set a small payload limit (1KB)
  22545. svr.set_payload_max_length(1024);
  22546. svr.Post("/test", [&](const Request &req, Response &res) {
  22547. res.set_content("Body size: " + std::to_string(req.body.size()),
  22548. "text/plain");
  22549. });
  22550. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22551. auto se = detail::scope_exit([&] {
  22552. svr.stop();
  22553. listen_thread.join();
  22554. });
  22555. svr.wait_until_ready();
  22556. // Create data that compresses well but exceeds limit when decompressed
  22557. // 8KB of repeated null bytes compresses to a very small size
  22558. std::string original_data(8 * 1024, '\0');
  22559. // Compress the data using gzip
  22560. std::string compressed_data;
  22561. detail::gzip_compressor compressor;
  22562. compressor.compress(original_data.data(), original_data.size(), true,
  22563. [&](const char *data, size_t size) {
  22564. compressed_data.append(data, size);
  22565. return true;
  22566. });
  22567. // Verify compression worked (compressed should be much smaller)
  22568. ASSERT_LT(compressed_data.size(), original_data.size());
  22569. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22570. // Send compressed data with Content-Encoding: gzip
  22571. Client cli(HOST, PORT);
  22572. Headers headers = {{"Content-Encoding", "gzip"}};
  22573. auto res =
  22574. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22575. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22577. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22578. }
  22579. #endif
  22580. // ============================================================================
  22581. // OpenSSL-Specific Tests
  22582. // ============================================================================
  22583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22584. X509 *readCertificate(const std::string &strFileName) {
  22585. std::ifstream inStream(strFileName);
  22586. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22587. std::istreambuf_iterator<char>());
  22588. if (strCertPEM.empty()) return (nullptr);
  22589. BIO *pbCert = BIO_new(BIO_s_mem());
  22590. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22591. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22592. BIO_free(pbCert);
  22593. return (pCert);
  22594. }
  22595. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22596. std::ifstream inStream(strFileName);
  22597. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22598. std::istreambuf_iterator<char>());
  22599. if (strPrivateKeyPEM.empty()) return (nullptr);
  22600. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22601. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22602. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22603. BIO_free(pbPrivKey);
  22604. return (pPrivateKey);
  22605. }
  22606. TEST(BindServerTest, UpdateCerts) {
  22607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22608. int port = svr.bind_to_any_port("0.0.0.0");
  22609. ASSERT_TRUE(svr.is_valid());
  22610. ASSERT_TRUE(port > 0);
  22611. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22612. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22613. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22614. ASSERT_TRUE(cert != nullptr);
  22615. ASSERT_TRUE(ca_cert != nullptr);
  22616. ASSERT_TRUE(key != nullptr);
  22617. X509_STORE *cert_store = X509_STORE_new();
  22618. X509_STORE_add_cert(cert_store, ca_cert);
  22619. // svr.update_certs(cert, key, cert_store); // deprecated
  22620. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22621. CLIENT_CA_CERT_FILE);
  22622. ASSERT_TRUE(svr.is_valid());
  22623. svr.stop();
  22624. X509_STORE_free(cert_store);
  22625. X509_free(cert);
  22626. X509_free(ca_cert);
  22627. EVP_PKEY_free(key);
  22628. }
  22629. // Test that update_certs() updates client CA list correctly
  22630. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22631. // Start with file-based constructor
  22632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22633. ASSERT_TRUE(svr.is_valid());
  22634. // Initially no client CA list should be set
  22635. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22636. ASSERT_TRUE(ssl_ctx != nullptr);
  22637. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22638. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22639. // Now update with client CA (PEM string)
  22640. std::string cert_pem, key_pem, ca_pem;
  22641. read_file(SERVER_CERT_FILE, cert_pem);
  22642. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22643. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22644. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22645. ASSERT_TRUE(svr.is_valid());
  22646. // Now client CA list should be set
  22647. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22648. ASSERT_TRUE(ca_list_after != nullptr);
  22649. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22650. }
  22651. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22652. // Test that the file-path SSLServer constructor properly sets the client CA
  22653. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22655. ASSERT_TRUE(svr.is_valid());
  22656. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22657. ASSERT_TRUE(ssl_ctx != nullptr);
  22658. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22659. ASSERT_TRUE(ca_list != nullptr);
  22660. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22661. }
  22662. #endif
  22663. // ============================================================================
  22664. // MbedTLS-Specific Tests
  22665. // ============================================================================
  22666. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22667. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22668. using namespace httplib::tls;
  22669. // Track if callback was invoked
  22670. bool callback_invoked = false;
  22671. // The callback receives void* ctx which is actually MbedTlsContext*
  22672. // We can access the mbedtls_ssl_config via the context
  22673. auto setup_callback = [&callback_invoked](void *ctx) {
  22674. callback_invoked = true;
  22675. // Cast to MbedTlsContext* to access the ssl config
  22676. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22677. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22678. // Use static variables to hold certificate data (simplified for test)
  22679. static mbedtls_x509_crt own_cert;
  22680. static mbedtls_pk_context own_key;
  22681. static mbedtls_x509_crt ca_chain;
  22682. static bool initialized = false;
  22683. if (!initialized) {
  22684. mbedtls_x509_crt_init(&own_cert);
  22685. mbedtls_pk_init(&own_key);
  22686. mbedtls_x509_crt_init(&ca_chain);
  22687. // Load server certificate
  22688. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22689. return false;
  22690. }
  22691. // Load server private key.
  22692. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22693. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22694. #if MBEDTLS_VERSION_MAJOR == 3
  22695. ,
  22696. mbedtls_ctr_drbg_random, nullptr
  22697. #endif
  22698. ) != 0) {
  22699. return false;
  22700. }
  22701. // Load CA chain for client verification
  22702. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22703. return false;
  22704. }
  22705. initialized = true;
  22706. }
  22707. // Configure the SSL config
  22708. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22709. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22710. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22711. // Set minimum TLS version using mbedTLS native API
  22712. #if MBEDTLS_VERSION_MAJOR >= 3
  22713. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22714. #else
  22715. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22716. MBEDTLS_SSL_MINOR_VERSION_3);
  22717. #endif
  22718. return true;
  22719. };
  22720. SSLServer svr(setup_callback);
  22721. ASSERT_TRUE(svr.is_valid());
  22722. ASSERT_TRUE(callback_invoked);
  22723. svr.Get("/test", [&](const Request &req, Response &res) {
  22724. res.set_content("test", "text/plain");
  22725. auto cert = req.peer_cert();
  22726. ASSERT_TRUE(static_cast<bool>(cert));
  22727. auto common_name = cert.subject_cn();
  22728. EXPECT_EQ("Common Name", common_name);
  22729. });
  22730. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22731. auto se = detail::scope_exit([&] {
  22732. svr.stop();
  22733. t.join();
  22734. ASSERT_FALSE(svr.is_running());
  22735. });
  22736. svr.wait_until_ready();
  22737. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22738. cli.enable_server_certificate_verification(false);
  22739. cli.set_connection_timeout(30);
  22740. auto res = cli.Get("/test");
  22741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22742. ASSERT_EQ(StatusCode::OK_200, res->status);
  22743. }
  22744. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22745. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22746. // keep-alive SSL session, which reads through that config in
  22747. // mbedtls_ssl_close_notify.
  22748. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22750. ASSERT_TRUE(svr.is_valid());
  22751. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22752. res.set_content("test", "text/plain");
  22753. });
  22754. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22755. auto se = detail::scope_exit([&] {
  22756. svr.stop();
  22757. t.join();
  22758. ASSERT_FALSE(svr.is_running());
  22759. });
  22760. svr.wait_until_ready();
  22761. {
  22762. SSLClient cli(HOST, PORT);
  22763. cli.enable_server_certificate_verification(false);
  22764. cli.set_keep_alive(true);
  22765. auto res = cli.Get("/test");
  22766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22767. ASSERT_EQ(StatusCode::OK_200, res->status);
  22768. // cli is destructed here with the keep-alive SSL session still open.
  22769. }
  22770. }
  22771. #endif
  22772. // WebSocket Tests
  22773. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22774. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22775. // defining the meaning of these bits has been negotiated.
  22776. auto make_frame = [](uint8_t first_byte) {
  22777. std::string frame;
  22778. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22779. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22780. frame += "Hello";
  22781. return frame;
  22782. };
  22783. // RSV1 set (0x40)
  22784. {
  22785. detail::BufferStream strm;
  22786. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22787. ws::Opcode opcode;
  22788. std::string payload;
  22789. bool fin;
  22790. EXPECT_EQ(
  22791. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22792. ws::impl::FrameRead::Fail);
  22793. }
  22794. // RSV2 set (0x20)
  22795. {
  22796. detail::BufferStream strm;
  22797. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22798. ws::Opcode opcode;
  22799. std::string payload;
  22800. bool fin;
  22801. EXPECT_EQ(
  22802. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22803. ws::impl::FrameRead::Fail);
  22804. }
  22805. // RSV3 set (0x10)
  22806. {
  22807. detail::BufferStream strm;
  22808. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22809. ws::Opcode opcode;
  22810. std::string payload;
  22811. bool fin;
  22812. EXPECT_EQ(
  22813. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22814. ws::impl::FrameRead::Fail);
  22815. }
  22816. // No RSV bits set - should succeed
  22817. {
  22818. detail::BufferStream strm;
  22819. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22820. ws::Opcode opcode;
  22821. std::string payload;
  22822. bool fin;
  22823. EXPECT_EQ(
  22824. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22825. ws::impl::FrameRead::Ok);
  22826. EXPECT_EQ(ws::Opcode::Text, opcode);
  22827. EXPECT_EQ("Hello", payload);
  22828. EXPECT_TRUE(fin);
  22829. }
  22830. }
  22831. TEST(WebSocketTest, ControlFrameValidation) {
  22832. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22833. // payload length <= 125.
  22834. // Ping with FIN=0 - must be rejected
  22835. {
  22836. detail::BufferStream strm;
  22837. std::string frame;
  22838. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22839. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22840. strm.write(frame.data(), frame.size());
  22841. ws::Opcode opcode;
  22842. std::string payload;
  22843. bool fin;
  22844. EXPECT_EQ(
  22845. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22846. ws::impl::FrameRead::Fail);
  22847. }
  22848. // Close with FIN=0 - must be rejected
  22849. {
  22850. detail::BufferStream strm;
  22851. std::string frame;
  22852. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22853. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22854. strm.write(frame.data(), frame.size());
  22855. ws::Opcode opcode;
  22856. std::string payload;
  22857. bool fin;
  22858. EXPECT_EQ(
  22859. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22860. ws::impl::FrameRead::Fail);
  22861. }
  22862. // Ping with payload_len=126 (extended length) - must be rejected
  22863. {
  22864. detail::BufferStream strm;
  22865. std::string frame;
  22866. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22867. frame += static_cast<char>(126); // payload_len=126 (>125)
  22868. frame += static_cast<char>(0x00); // extended length high byte
  22869. frame += static_cast<char>(126); // extended length low byte
  22870. frame += std::string(126, 'x');
  22871. strm.write(frame.data(), frame.size());
  22872. ws::Opcode opcode;
  22873. std::string payload;
  22874. bool fin;
  22875. EXPECT_EQ(
  22876. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22877. ws::impl::FrameRead::Fail);
  22878. }
  22879. // Ping with FIN=1 and payload_len=125 - should succeed
  22880. {
  22881. detail::BufferStream strm;
  22882. std::string frame;
  22883. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22884. frame += static_cast<char>(125); // payload_len=125
  22885. frame += std::string(125, 'x');
  22886. strm.write(frame.data(), frame.size());
  22887. ws::Opcode opcode;
  22888. std::string payload;
  22889. bool fin;
  22890. EXPECT_EQ(
  22891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22892. ws::impl::FrameRead::Ok);
  22893. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22894. EXPECT_EQ(125u, payload.size());
  22895. EXPECT_TRUE(fin);
  22896. }
  22897. }
  22898. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22899. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22900. // length MUST be 0.
  22901. // MSB set - must be rejected
  22902. {
  22903. detail::BufferStream strm;
  22904. std::string frame;
  22905. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22906. frame += static_cast<char>(127); // 64-bit extended length
  22907. frame += static_cast<char>(0x80); // MSB set (invalid)
  22908. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22909. strm.write(frame.data(), frame.size());
  22910. ws::Opcode opcode;
  22911. std::string payload;
  22912. bool fin;
  22913. EXPECT_EQ(
  22914. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22915. ws::impl::FrameRead::Fail);
  22916. }
  22917. // MSB clear - should pass length parsing (will be rejected by max_len,
  22918. // but that's a different check; use a small length to verify)
  22919. {
  22920. detail::BufferStream strm;
  22921. std::string frame;
  22922. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22923. frame += static_cast<char>(127); // 64-bit extended length
  22924. frame += std::string(7, '\0'); // high bytes = 0
  22925. frame += static_cast<char>(0x03); // length = 3
  22926. frame += "abc";
  22927. strm.write(frame.data(), frame.size());
  22928. ws::Opcode opcode;
  22929. std::string payload;
  22930. bool fin;
  22931. EXPECT_EQ(
  22932. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22933. ws::impl::FrameRead::Ok);
  22934. EXPECT_EQ(ws::Opcode::Text, opcode);
  22935. EXPECT_EQ("abc", payload);
  22936. }
  22937. }
  22938. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22939. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22940. // Valid UTF-8
  22941. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22942. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22943. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22944. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22945. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22946. // Invalid UTF-8
  22947. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22948. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22949. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22950. EXPECT_FALSE(
  22951. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22952. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22953. }
  22954. TEST(WebSocketTest, ConnectAndDisconnect) {
  22955. Server svr;
  22956. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22957. std::string msg;
  22958. while (ws.read(msg)) {}
  22959. });
  22960. auto port = svr.bind_to_any_port(HOST);
  22961. std::thread t([&]() { svr.listen_after_bind(); });
  22962. svr.wait_until_ready();
  22963. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22964. auto res = client.connect();
  22965. ASSERT_TRUE(res);
  22966. EXPECT_EQ(Error::Success, res.error());
  22967. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22968. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22969. EXPECT_TRUE(client.is_open());
  22970. client.close();
  22971. EXPECT_FALSE(client.is_open());
  22972. svr.stop();
  22973. t.join();
  22974. }
  22975. TEST(WebSocketTest, ValidURL) {
  22976. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22977. EXPECT_TRUE(ws1.is_valid());
  22978. ws::WebSocketClient ws2("ws://example.com/path");
  22979. EXPECT_TRUE(ws2.is_valid());
  22980. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22981. EXPECT_TRUE(ws3.is_valid());
  22982. #ifdef CPPHTTPLIB_SSL_ENABLED
  22983. ws::WebSocketClient wss1("wss://example.com/path");
  22984. EXPECT_TRUE(wss1.is_valid());
  22985. ws::WebSocketClient wss2("wss://example.com:443/path");
  22986. EXPECT_TRUE(wss2.is_valid());
  22987. #endif
  22988. }
  22989. TEST(WebSocketTest, InvalidURL) {
  22990. // No scheme
  22991. ws::WebSocketClient ws1("localhost:8080/path");
  22992. EXPECT_FALSE(ws1.is_valid());
  22993. // No path
  22994. ws::WebSocketClient ws2("ws://localhost:8080");
  22995. EXPECT_FALSE(ws2.is_valid());
  22996. // Empty string
  22997. ws::WebSocketClient ws3("");
  22998. EXPECT_FALSE(ws3.is_valid());
  22999. // Missing host
  23000. ws::WebSocketClient ws4("ws://:8080/path");
  23001. EXPECT_FALSE(ws4.is_valid());
  23002. // Port number overflow — should not crash
  23003. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23004. EXPECT_FALSE(ws5.is_valid());
  23005. // Port out of range
  23006. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23007. EXPECT_FALSE(ws6.is_valid());
  23008. }
  23009. TEST(WebSocketTest, UnsupportedScheme) {
  23010. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23011. ws::WebSocketClient ws1("http://localhost:8080/path");
  23012. EXPECT_FALSE(ws1.is_valid());
  23013. ws::WebSocketClient ws2("https://localhost:8080/path");
  23014. EXPECT_FALSE(ws2.is_valid());
  23015. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23016. EXPECT_FALSE(ws3.is_valid());
  23017. #else
  23018. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23019. std::invalid_argument);
  23020. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23021. std::invalid_argument);
  23022. #endif
  23023. }
  23024. TEST(WebSocketTest, ConnectWhenInvalid) {
  23025. ws::WebSocketClient ws("not a valid url");
  23026. EXPECT_FALSE(ws.is_valid());
  23027. auto res = ws.connect();
  23028. EXPECT_FALSE(res);
  23029. EXPECT_EQ(Error::Connection, res.error());
  23030. EXPECT_EQ(-1, res.status());
  23031. }
  23032. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23033. // Grab a port that is free, then close it again so nothing listens there
  23034. Server svr;
  23035. auto port = svr.bind_to_any_port(HOST);
  23036. svr.stop();
  23037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23038. auto res = client.connect();
  23039. ASSERT_FALSE(res);
  23040. EXPECT_EQ(Error::Connection, res.error());
  23041. EXPECT_EQ(-1, res.status());
  23042. }
  23043. TEST(WebSocketTest, DefaultPort) {
  23044. ws::WebSocketClient ws1("ws://example.com/path");
  23045. EXPECT_TRUE(ws1.is_valid());
  23046. // ws:// defaults to port 80 (verified by successful parse)
  23047. #ifdef CPPHTTPLIB_SSL_ENABLED
  23048. ws::WebSocketClient ws2("wss://example.com/path");
  23049. EXPECT_TRUE(ws2.is_valid());
  23050. // wss:// defaults to port 443 (verified by successful parse)
  23051. #endif
  23052. }
  23053. TEST(WebSocketTest, IPv6LiteralAddress) {
  23054. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23055. EXPECT_TRUE(ws1.is_valid());
  23056. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23057. EXPECT_TRUE(ws2.is_valid());
  23058. }
  23059. TEST(WebSocketTest, ComplexPath) {
  23060. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23061. EXPECT_TRUE(ws1.is_valid());
  23062. ws::WebSocketClient ws2("ws://localhost:8080/");
  23063. EXPECT_TRUE(ws2.is_valid());
  23064. }
  23065. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23066. Server svr;
  23067. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23068. std::string msg;
  23069. while (ws.read(msg)) {}
  23070. });
  23071. auto port = svr.bind_to_any_port(HOST);
  23072. std::thread t([&]() { svr.listen_after_bind(); });
  23073. svr.wait_until_ready();
  23074. auto another_host = "example.com";
  23075. auto wrong_ip = "192.0.2.1";
  23076. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23077. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23078. ASSERT_TRUE(client.connect());
  23079. EXPECT_TRUE(client.is_open());
  23080. client.close();
  23081. svr.stop();
  23082. t.join();
  23083. }
  23084. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23085. Server svr;
  23086. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23087. std::string msg;
  23088. while (ws.read(msg)) {}
  23089. });
  23090. auto port = svr.bind_to_any_port(HOST);
  23091. std::thread t([&]() { svr.listen_after_bind(); });
  23092. svr.wait_until_ready();
  23093. auto wrong_ip = "192.0.2.1";
  23094. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23095. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23096. client.set_connection_timeout(1);
  23097. client.set_read_timeout(1);
  23098. client.set_write_timeout(1);
  23099. EXPECT_FALSE(client.connect());
  23100. EXPECT_FALSE(client.is_open());
  23101. svr.stop();
  23102. t.join();
  23103. }
  23104. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23105. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23106. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23107. // (RFC 6761) is only a map key and the Host header value.
  23108. auto host = "target.invalid";
  23109. Server svr;
  23110. std::string received_host;
  23111. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23112. received_host = req.get_header_value("Host");
  23113. std::string msg;
  23114. while (ws.read(msg)) {}
  23115. });
  23116. auto port = svr.bind_to_any_port(HOST);
  23117. std::thread t([&]() { svr.listen_after_bind(); });
  23118. // ASSERT_* below returns from the test body, which would leave t joinable
  23119. // and make ~thread call std::terminate.
  23120. auto se = detail::scope_exit([&] {
  23121. svr.stop();
  23122. if (t.joinable()) { t.join(); }
  23123. });
  23124. svr.wait_until_ready();
  23125. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23126. std::to_string(port) + "/ws");
  23127. client.set_hostname_addr_map({{host, HOST}});
  23128. ASSERT_TRUE(client.connect());
  23129. EXPECT_TRUE(client.is_open());
  23130. client.close();
  23131. svr.stop();
  23132. t.join();
  23133. // The mapping only redirects the connection; the identity stays host_.
  23134. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23135. }
  23136. class WebSocketIntegrationTest : public ::testing::Test {
  23137. protected:
  23138. void SetUp() override {
  23139. server_ = httplib::detail::make_unique<Server>();
  23140. setup_server();
  23141. start_server();
  23142. }
  23143. void TearDown() override {
  23144. server_->stop();
  23145. if (server_thread_.joinable()) { server_thread_.join(); }
  23146. }
  23147. void setup_server() {
  23148. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23149. std::string msg;
  23150. ws::ReadResult ret;
  23151. while ((ret = ws.read(msg))) {
  23152. if (ret == ws::Binary) {
  23153. ws.send(msg.data(), msg.size());
  23154. } else {
  23155. ws.send(msg);
  23156. }
  23157. }
  23158. });
  23159. server_->WebSocket("/ws-echo-string",
  23160. [](const Request &, ws::WebSocket &ws) {
  23161. std::string msg;
  23162. while (ws.read(msg)) {
  23163. ws.send("echo: " + msg);
  23164. }
  23165. });
  23166. server_->WebSocket(
  23167. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23168. // Echo back request metadata
  23169. ws.send("path:" + req.path);
  23170. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23171. std::string msg;
  23172. while (ws.read(msg)) {}
  23173. });
  23174. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23175. std::string msg;
  23176. ws.read(msg); // wait for a message
  23177. ws.close();
  23178. });
  23179. server_->WebSocket("/ws-close-status",
  23180. [](const Request &, ws::WebSocket &ws) {
  23181. std::string msg;
  23182. ws.read(msg); // wait for a message
  23183. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23184. });
  23185. server_->WebSocket(
  23186. "/ws-subprotocol",
  23187. [](const Request &, ws::WebSocket &ws) {
  23188. std::string msg;
  23189. while (ws.read(msg)) {
  23190. ws.send(msg);
  23191. }
  23192. },
  23193. [](const std::vector<std::string> &protocols) -> std::string {
  23194. for (const auto &p : protocols) {
  23195. if (p == "graphql-ws") { return p; }
  23196. }
  23197. return "";
  23198. });
  23199. server_->WebSocket(
  23200. "/ws-subprotocol-unoffered",
  23201. [](const Request &, ws::WebSocket &ws) {
  23202. std::string msg;
  23203. while (ws.read(msg)) {
  23204. ws.send(msg);
  23205. }
  23206. },
  23207. [](const std::vector<std::string> &) -> std::string {
  23208. return "admin";
  23209. });
  23210. }
  23211. void start_server() {
  23212. port_ = server_->bind_to_any_port(HOST);
  23213. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23214. server_->wait_until_ready();
  23215. }
  23216. std::unique_ptr<Server> server_;
  23217. std::thread server_thread_;
  23218. int port_ = 0;
  23219. };
  23220. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23222. "/ws-echo");
  23223. ASSERT_TRUE(client.connect());
  23224. ASSERT_TRUE(client.is_open());
  23225. ASSERT_TRUE(client.send("Hello WebSocket"));
  23226. std::string msg;
  23227. EXPECT_EQ(ws::Text, client.read(msg));
  23228. EXPECT_EQ("Hello WebSocket", msg);
  23229. client.close();
  23230. }
  23231. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23233. "/ws-echo");
  23234. ASSERT_TRUE(client.connect());
  23235. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23236. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23237. std::string msg;
  23238. EXPECT_EQ(ws::Binary, client.read(msg));
  23239. EXPECT_EQ(binary_data, msg);
  23240. client.close();
  23241. }
  23242. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23243. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23244. "/ws-echo");
  23245. ASSERT_TRUE(client.connect());
  23246. for (int i = 0; i < 10; i++) {
  23247. auto text = "message " + std::to_string(i);
  23248. ASSERT_TRUE(client.send(text));
  23249. std::string msg;
  23250. ASSERT_TRUE(client.read(msg));
  23251. EXPECT_EQ(text, msg);
  23252. }
  23253. client.close();
  23254. }
  23255. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23256. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23257. "/ws-close");
  23258. ASSERT_TRUE(client.connect());
  23259. // Send a message to trigger the server to close
  23260. ASSERT_TRUE(client.send("trigger close"));
  23261. // The server will close, so read should return false
  23262. std::string msg;
  23263. EXPECT_FALSE(client.read(msg));
  23264. EXPECT_FALSE(client.is_open());
  23265. }
  23266. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23268. "/ws-echo");
  23269. ASSERT_TRUE(client.connect());
  23270. // 128KB message
  23271. std::string large_data(128 * 1024, 'X');
  23272. ASSERT_TRUE(client.send(large_data));
  23273. std::string msg;
  23274. ASSERT_TRUE(client.read(msg));
  23275. EXPECT_EQ(large_data, msg);
  23276. client.close();
  23277. }
  23278. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23280. "/ws-echo");
  23281. ASSERT_TRUE(client.connect());
  23282. const int num_threads = 4;
  23283. std::vector<std::thread> threads;
  23284. std::atomic<int> send_count{0};
  23285. for (int t = 0; t < num_threads; t++) {
  23286. threads.emplace_back([&client, &send_count, t]() {
  23287. for (int i = 0; i < 5; i++) {
  23288. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23289. if (client.send(text)) { send_count++; }
  23290. }
  23291. });
  23292. }
  23293. for (auto &th : threads) {
  23294. th.join();
  23295. }
  23296. int received = 0;
  23297. std::string msg;
  23298. while (received < send_count.load()) {
  23299. if (!client.read(msg)) { break; }
  23300. received++;
  23301. }
  23302. EXPECT_EQ(send_count.load(), received);
  23303. client.close();
  23304. }
  23305. TEST_F(WebSocketIntegrationTest, ReadString) {
  23306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23307. "/ws-echo-string");
  23308. ASSERT_TRUE(client.connect());
  23309. ASSERT_TRUE(client.send("hello"));
  23310. std::string msg;
  23311. ASSERT_TRUE(client.read(msg));
  23312. EXPECT_EQ("echo: hello", msg);
  23313. ASSERT_TRUE(client.send("world"));
  23314. ASSERT_TRUE(client.read(msg));
  23315. EXPECT_EQ("echo: world", msg);
  23316. client.close();
  23317. }
  23318. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23319. Headers headers = {{"X-Test-Header", "test-value"}};
  23320. ws::WebSocketClient client(
  23321. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23322. ASSERT_TRUE(client.connect());
  23323. std::string msg;
  23324. ASSERT_TRUE(client.read(msg));
  23325. EXPECT_EQ("path:/ws-request-info", msg);
  23326. ASSERT_TRUE(client.read(msg));
  23327. EXPECT_EQ("header:test-value", msg);
  23328. client.close();
  23329. }
  23330. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23331. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23332. "/ws-echo");
  23333. client.set_read_timeout(1, 0); // 1 second
  23334. ASSERT_TRUE(client.connect());
  23335. // Don't send anything — server echo handler waits for a message, so read()
  23336. // should time out. The connection survives it: nothing was consumed.
  23337. std::string msg;
  23338. EXPECT_EQ(client.read(msg), ws::Timeout);
  23339. EXPECT_TRUE(client.is_open());
  23340. // And it is still usable afterwards.
  23341. EXPECT_TRUE(client.send("after timeout"));
  23342. EXPECT_EQ(client.read(msg), ws::Text);
  23343. EXPECT_EQ(msg, "after timeout");
  23344. }
  23345. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23347. "/ws-echo");
  23348. client.set_read_timeout(1, 0);
  23349. ASSERT_TRUE(client.connect());
  23350. ASSERT_TRUE(client.send("first"));
  23351. std::string msg;
  23352. ASSERT_EQ(client.read(msg), ws::Text);
  23353. ASSERT_EQ(msg, "first");
  23354. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23355. // not be used with a read timeout: it would reprocess the previous message.
  23356. EXPECT_EQ(client.read(msg), ws::Timeout);
  23357. EXPECT_EQ(msg, "first");
  23358. }
  23359. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23360. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23361. "/ws-echo");
  23362. ASSERT_TRUE(client.connect());
  23363. // Setting it once the connection is open reaches the live stream, not just
  23364. // the seed for the next connect().
  23365. client.set_read_timeout(1, 0);
  23366. std::string msg;
  23367. EXPECT_EQ(client.read(msg), ws::Timeout);
  23368. EXPECT_TRUE(client.is_open());
  23369. }
  23370. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23371. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23372. "/ws-echo");
  23373. client.set_read_timeout(5, 0);
  23374. ASSERT_TRUE(client.connect());
  23375. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23376. // The server should reject it and close the connection.
  23377. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23378. client.send(oversized);
  23379. // The server's read() should have failed due to payload limit,
  23380. // so our read() should return false (connection closed).
  23381. std::string msg;
  23382. EXPECT_FALSE(client.read(msg));
  23383. }
  23384. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23386. "/ws-echo");
  23387. client.set_read_timeout(10, 0);
  23388. ASSERT_TRUE(client.connect());
  23389. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23390. // This should succeed.
  23391. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23392. ASSERT_TRUE(client.send(at_limit));
  23393. std::string msg;
  23394. ASSERT_TRUE(client.read(msg));
  23395. EXPECT_EQ(at_limit.size(), msg.size());
  23396. client.close();
  23397. }
  23398. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23400. "/nonexistent");
  23401. auto res = client.connect();
  23402. EXPECT_FALSE(res);
  23403. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23404. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23405. EXPECT_FALSE(client.is_open());
  23406. }
  23407. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23409. "/ws-echo");
  23410. ASSERT_TRUE(client.connect());
  23411. ASSERT_TRUE(client.send(""));
  23412. std::string msg;
  23413. EXPECT_EQ(ws::Text, client.read(msg));
  23414. EXPECT_EQ("", msg);
  23415. client.close();
  23416. }
  23417. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23419. "/ws-echo");
  23420. // First connection
  23421. ASSERT_TRUE(client.connect());
  23422. ASSERT_TRUE(client.send("first"));
  23423. std::string msg;
  23424. ASSERT_TRUE(client.read(msg));
  23425. EXPECT_EQ("first", msg);
  23426. client.close();
  23427. EXPECT_FALSE(client.is_open());
  23428. // Reconnect using the same client object
  23429. ASSERT_TRUE(client.connect());
  23430. ASSERT_TRUE(client.is_open());
  23431. ASSERT_TRUE(client.send("second"));
  23432. ASSERT_TRUE(client.read(msg));
  23433. EXPECT_EQ("second", msg);
  23434. client.close();
  23435. }
  23436. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23438. "/ws-close-status");
  23439. ASSERT_TRUE(client.connect());
  23440. // Trigger the server to close with GoingAway status
  23441. ASSERT_TRUE(client.send("trigger"));
  23442. // read() should return false after receiving the close frame
  23443. std::string msg;
  23444. EXPECT_FALSE(client.read(msg));
  23445. EXPECT_FALSE(client.is_open());
  23446. }
  23447. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23448. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23449. "/ws-echo");
  23450. ASSERT_TRUE(client.connect());
  23451. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23452. EXPECT_FALSE(client.is_open());
  23453. }
  23454. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23455. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23456. ws::WebSocketClient client(
  23457. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23458. ASSERT_TRUE(client.connect());
  23459. // Server should have selected graphql-ws
  23460. EXPECT_EQ("graphql-ws", client.subprotocol());
  23461. client.close();
  23462. }
  23463. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23464. Headers headers;
  23465. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23466. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23467. ws::WebSocketClient client(
  23468. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23469. ASSERT_TRUE(client.connect());
  23470. // The offer on the second field line counts too, so graphql-ws is selected
  23471. EXPECT_EQ("graphql-ws", client.subprotocol());
  23472. client.close();
  23473. }
  23474. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23475. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23476. ws::WebSocketClient client(
  23477. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23478. ASSERT_TRUE(client.connect());
  23479. // Server should not have selected any subprotocol
  23480. EXPECT_TRUE(client.subprotocol().empty());
  23481. client.close();
  23482. }
  23483. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23484. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23485. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23486. "/ws-subprotocol-unoffered",
  23487. headers);
  23488. ASSERT_TRUE(client.connect());
  23489. EXPECT_TRUE(client.subprotocol().empty());
  23490. client.close();
  23491. }
  23492. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23493. // Connect without requesting any subprotocol
  23494. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23495. "/ws-subprotocol");
  23496. ASSERT_TRUE(client.connect());
  23497. EXPECT_TRUE(client.subprotocol().empty());
  23498. client.close();
  23499. }
  23500. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23501. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23502. "/ws-echo");
  23503. client.set_tcp_nodelay(true);
  23504. client.set_connection_timeout(3, 0);
  23505. bool socket_options_called = false;
  23506. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23507. ASSERT_TRUE(client.connect());
  23508. ASSERT_TRUE(client.is_open());
  23509. EXPECT_TRUE(socket_options_called);
  23510. ASSERT_TRUE(client.send("hello"));
  23511. std::string msg;
  23512. auto result = client.read(msg);
  23513. EXPECT_EQ(result, ws::ReadResult::Text);
  23514. EXPECT_EQ(msg, "hello");
  23515. client.close();
  23516. }
  23517. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23518. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23519. "/ws-echo");
  23520. client.set_connection_timeout(std::chrono::seconds(3));
  23521. client.set_write_timeout(std::chrono::seconds(3));
  23522. // A sub-second remainder exercises the seconds/microseconds split.
  23523. client.set_read_timeout(std::chrono::milliseconds(1500));
  23524. ASSERT_TRUE(client.connect());
  23525. auto start = std::chrono::steady_clock::now();
  23526. std::string msg;
  23527. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23528. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23529. std::chrono::steady_clock::now() - start)
  23530. .count();
  23531. // Above 1s so that dropping the microseconds half of the split fails here.
  23532. // Ignoring the setter altogether would not reach this line at all: a client
  23533. // waits forever by default.
  23534. EXPECT_GE(elapsed, 1400);
  23535. EXPECT_LT(elapsed, 30000);
  23536. }
  23537. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23538. Server svr;
  23539. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23540. if (!req.has_header("Authorization")) {
  23541. res.status = StatusCode::Unauthorized_401;
  23542. res.set_content("Unauthorized", "text/plain");
  23543. return Server::HandlerResponse::Handled;
  23544. }
  23545. return Server::HandlerResponse::Unhandled;
  23546. });
  23547. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23548. std::string msg;
  23549. while (ws.read(msg)) {
  23550. ws.send(msg);
  23551. }
  23552. });
  23553. auto port = svr.bind_to_any_port("localhost");
  23554. std::thread t([&]() { svr.listen_after_bind(); });
  23555. svr.wait_until_ready();
  23556. // Without Authorization header - should be rejected before upgrade
  23557. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23558. EXPECT_FALSE(client1.connect());
  23559. // The rejection is framed like any other HTTP response
  23560. {
  23561. Client cli("localhost", port);
  23562. Headers headers = {{"Upgrade", "websocket"},
  23563. {"Connection", "Upgrade"},
  23564. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23565. {"Sec-WebSocket-Version", "13"}};
  23566. auto res = cli.Get("/ws", headers);
  23567. ASSERT_TRUE(res);
  23568. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23569. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23570. EXPECT_EQ("Unauthorized", res->body);
  23571. }
  23572. // With Authorization header - should succeed
  23573. Headers headers = {{"Authorization", "Bearer token123"}};
  23574. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23575. headers);
  23576. ASSERT_TRUE(client2.connect());
  23577. ASSERT_TRUE(client2.send("hello"));
  23578. std::string msg;
  23579. ASSERT_TRUE(client2.read(msg));
  23580. EXPECT_EQ("hello", msg);
  23581. client2.close();
  23582. svr.stop();
  23583. t.join();
  23584. }
  23585. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23586. Server svr;
  23587. std::atomic<int> pre_routing_calls{0};
  23588. std::atomic<int> pre_request_calls{0};
  23589. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23590. pre_routing_calls++;
  23591. if (req.path == "/handled") {
  23592. res.set_content("handled", "text/plain");
  23593. return Server::HandlerResponse::Handled;
  23594. }
  23595. return Server::HandlerResponse::Unhandled;
  23596. });
  23597. svr.set_pre_request_handler([&](const Request &, Response &) {
  23598. pre_request_calls++;
  23599. return Server::HandlerResponse::Unhandled;
  23600. });
  23601. svr.Get("/http", [](const Request &, Response &res) {
  23602. res.set_content("http", "text/plain");
  23603. });
  23604. svr.WebSocket("/ws",
  23605. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23606. auto port = svr.bind_to_any_port("localhost");
  23607. std::thread t([&]() { svr.listen_after_bind(); });
  23608. auto se = detail::scope_exit([&] {
  23609. svr.stop();
  23610. t.join();
  23611. });
  23612. svr.wait_until_ready();
  23613. Headers upgrade = {{"Upgrade", "websocket"},
  23614. {"Connection", "Upgrade"},
  23615. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23616. {"Sec-WebSocket-Version", "13"}};
  23617. auto get = [&](const char *path) {
  23618. pre_routing_calls = 0;
  23619. return Client("localhost", port).Get(path, upgrade);
  23620. };
  23621. // No WebSocket route, but an HTTP one
  23622. auto res = get("/http");
  23623. ASSERT_TRUE(res);
  23624. EXPECT_EQ(StatusCode::OK_200, res->status);
  23625. EXPECT_EQ("http", res->body);
  23626. EXPECT_EQ(1, pre_routing_calls);
  23627. EXPECT_EQ(1, pre_request_calls);
  23628. // No route at all
  23629. res = get("/none");
  23630. ASSERT_TRUE(res);
  23631. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23632. EXPECT_EQ(1, pre_routing_calls);
  23633. // Answered by the pre-routing handler
  23634. res = get("/handled");
  23635. ASSERT_TRUE(res);
  23636. EXPECT_EQ(StatusCode::OK_200, res->status);
  23637. EXPECT_EQ("handled", res->body);
  23638. EXPECT_EQ(1, pre_routing_calls);
  23639. // A WebSocket route
  23640. pre_routing_calls = 0;
  23641. pre_request_calls = 0;
  23642. {
  23643. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23644. "/ws");
  23645. ASSERT_TRUE(client.connect());
  23646. std::string msg;
  23647. ASSERT_TRUE(client.read(msg));
  23648. EXPECT_EQ("ws", msg);
  23649. client.close();
  23650. }
  23651. EXPECT_EQ(1, pre_routing_calls);
  23652. EXPECT_EQ(1, pre_request_calls);
  23653. }
  23654. // An upgrade request answered by a hook leaves its body unread, so that body
  23655. // must not be served as the next request on the connection.
  23656. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23657. Server svr;
  23658. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23659. if (req.path == "/pre-routing") {
  23660. res.set_content("pre-routing", "text/plain");
  23661. return Server::HandlerResponse::Handled;
  23662. }
  23663. return Server::HandlerResponse::Unhandled;
  23664. });
  23665. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23666. if (req.matched_route == "/pre-request") {
  23667. res.set_content("pre-request", "text/plain");
  23668. return Server::HandlerResponse::Handled;
  23669. }
  23670. return Server::HandlerResponse::Unhandled;
  23671. });
  23672. svr.Get("/smuggled", [](const Request &, Response &res) {
  23673. res.set_content("smuggled", "text/plain");
  23674. });
  23675. svr.WebSocket("/pre-request",
  23676. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23677. auto port = svr.bind_to_any_port(HOST);
  23678. std::thread t([&]() { svr.listen_after_bind(); });
  23679. auto se = detail::scope_exit([&] {
  23680. svr.stop();
  23681. t.join();
  23682. });
  23683. svr.wait_until_ready();
  23684. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23685. for (auto path : {"/pre-routing", "/pre-request"}) {
  23686. std::string req = std::string("GET ") + path +
  23687. " HTTP/1.1\r\n"
  23688. "Host: localhost\r\n"
  23689. "Upgrade: websocket\r\n"
  23690. "Connection: Upgrade\r\n"
  23691. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23692. "Sec-WebSocket-Version: 13\r\n"
  23693. "Content-Length: " +
  23694. std::to_string(body.size()) + "\r\n\r\n" + body;
  23695. std::string res;
  23696. ASSERT_TRUE(send_request(5, req, &res, port));
  23697. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23698. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23699. // Only one response, and the body was not served as a request
  23700. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23701. }
  23702. }
  23703. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23704. Server svr;
  23705. std::atomic<int> pre_request_calls{0};
  23706. std::atomic<bool> route_matched{false};
  23707. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23708. pre_request_calls++;
  23709. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23710. if (req.get_header_value("Authorization") != "Bearer token123") {
  23711. res.status = StatusCode::Unauthorized_401;
  23712. res.set_content("Unauthorized", "text/plain");
  23713. return Server::HandlerResponse::Handled;
  23714. }
  23715. return Server::HandlerResponse::Unhandled;
  23716. });
  23717. std::atomic<bool> handler_called{false};
  23718. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23719. handler_called = true;
  23720. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23721. });
  23722. auto port = svr.bind_to_any_port("localhost");
  23723. std::thread t([&]() { svr.listen_after_bind(); });
  23724. svr.wait_until_ready();
  23725. // Without Authorization header - should be rejected before upgrade
  23726. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23727. "/ws/1");
  23728. EXPECT_FALSE(client1.connect());
  23729. EXPECT_FALSE(handler_called);
  23730. EXPECT_EQ(1, pre_request_calls);
  23731. EXPECT_TRUE(route_matched);
  23732. // The rejection is an ordinary HTTP response, not a protocol switch
  23733. {
  23734. Client cli("localhost", port);
  23735. Headers headers = {{"Upgrade", "websocket"},
  23736. {"Connection", "Upgrade"},
  23737. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23738. {"Sec-WebSocket-Version", "13"}};
  23739. auto res = cli.Get("/ws/1", headers);
  23740. ASSERT_TRUE(res);
  23741. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23742. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23743. EXPECT_EQ("Unauthorized", res->body);
  23744. }
  23745. EXPECT_FALSE(handler_called);
  23746. // With Authorization header - should succeed
  23747. Headers headers = {{"Authorization", "Bearer token123"}};
  23748. ws::WebSocketClient client2(
  23749. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23750. ASSERT_TRUE(client2.connect());
  23751. std::string msg;
  23752. ASSERT_TRUE(client2.read(msg));
  23753. EXPECT_EQ("/ws/:id 2", msg);
  23754. EXPECT_TRUE(handler_called);
  23755. client2.close();
  23756. svr.stop();
  23757. t.join();
  23758. }
  23759. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23760. Server svr;
  23761. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23762. // A read timeout is how a handler gets control back. Without it, a handler
  23763. // parked in read() can never write on the connection it is reading.
  23764. ws.set_read_timeout(std::chrono::milliseconds(100));
  23765. std::string msg;
  23766. while (ws.is_open()) {
  23767. auto r = ws.read(msg);
  23768. if (r == httplib::ws::Timeout) {
  23769. ws.send("tick");
  23770. continue;
  23771. }
  23772. if (r == httplib::ws::Fail) { break; }
  23773. ws.send(msg);
  23774. }
  23775. });
  23776. auto port = svr.bind_to_any_port("localhost");
  23777. std::thread t([&]() { svr.listen_after_bind(); });
  23778. svr.wait_until_ready();
  23779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23780. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23781. ASSERT_TRUE(client.connect());
  23782. // The client sends nothing, so anything it receives came out of the
  23783. // handler's timeout path.
  23784. std::string msg;
  23785. ASSERT_EQ(client.read(msg), ws::Text);
  23786. EXPECT_EQ("tick", msg);
  23787. client.close();
  23788. svr.stop();
  23789. t.join();
  23790. }
  23791. // Stream::read may return fewer bytes than asked for. This is that contract at
  23792. // its worst -- one byte per call -- which is what a frame header straddling a
  23793. // read buffer's boundary looks like to the frame parser.
  23794. class WsByteAtATimeStream : public Stream {
  23795. public:
  23796. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23797. bool is_readable() const override { return true; }
  23798. bool wait_readable() const override { return true; }
  23799. bool wait_writable() const override { return true; }
  23800. ssize_t read(char *ptr, size_t size) override {
  23801. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23802. *ptr = data_[pos_++];
  23803. return 1;
  23804. }
  23805. ssize_t write(const char *, size_t size) override {
  23806. return static_cast<ssize_t>(size);
  23807. }
  23808. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23809. ip = "127.0.0.1";
  23810. port = 0;
  23811. }
  23812. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23813. ip = "127.0.0.1";
  23814. port = 0;
  23815. }
  23816. socket_t socket() const override { return INVALID_SOCKET; }
  23817. time_t duration() const override { return 0; }
  23818. private:
  23819. std::string data_;
  23820. size_t pos_ = 0;
  23821. };
  23822. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23823. // The payload uses the 16-bit extended length, so the header, the length
  23824. // and the mask key are all multi-byte fields here. Each used to be read
  23825. // with a single read() call, which fails as soon as one is split. The
  23826. // payload is also a little over one read chunk, so it is read in two.
  23827. std::string body;
  23828. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23829. body += static_cast<char>(i % 251);
  23830. }
  23831. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23832. std::string frame;
  23833. frame += static_cast<char>(0x81); // FIN + Text
  23834. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23835. frame += static_cast<char>(body.size() >> 8);
  23836. frame += static_cast<char>(body.size() & 0xff);
  23837. for (size_t i = 0; i < 4; i++) {
  23838. frame += static_cast<char>(mask[i]);
  23839. }
  23840. for (size_t i = 0; i < body.size(); i++) {
  23841. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23842. }
  23843. WsByteAtATimeStream strm(frame);
  23844. ws::Opcode opcode;
  23845. std::string payload;
  23846. bool fin = false;
  23847. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23848. /*expect_masked=*/true, body.size()),
  23849. ws::impl::FrameRead::Ok);
  23850. EXPECT_TRUE(fin);
  23851. EXPECT_EQ(opcode, ws::Opcode::Text);
  23852. EXPECT_EQ(payload, body);
  23853. }
  23854. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23855. std::string body(2000, 'x');
  23856. std::string frame;
  23857. frame += static_cast<char>(0x82); // FIN + Binary
  23858. frame += static_cast<char>(126); // 16-bit length follows
  23859. frame += static_cast<char>(body.size() >> 8);
  23860. frame += static_cast<char>(body.size() & 0xff);
  23861. frame += body;
  23862. detail::BufferStream strm;
  23863. strm.write(frame.data(), frame.size());
  23864. ws::Opcode opcode;
  23865. std::string payload;
  23866. bool fin;
  23867. EXPECT_EQ(
  23868. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23869. ws::impl::FrameRead::Ok);
  23870. EXPECT_EQ(body, payload);
  23871. }
  23872. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23873. // The header announces the largest payload allowed, and only 3 bytes of it
  23874. // ever arrive.
  23875. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23876. std::string frame;
  23877. frame += static_cast<char>(0x82); // FIN + Binary
  23878. frame += static_cast<char>(127); // 64-bit length follows
  23879. for (int shift = 56; shift >= 0; shift -= 8) {
  23880. frame += static_cast<char>((len >> shift) & 0xff);
  23881. }
  23882. frame += "abc";
  23883. detail::BufferStream strm;
  23884. strm.write(frame.data(), frame.size());
  23885. ws::Opcode opcode;
  23886. std::string payload;
  23887. bool fin;
  23888. EXPECT_EQ(
  23889. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23890. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23891. ws::impl::FrameRead::Fail);
  23892. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23893. }
  23894. TEST(WebSocketTest, QueryStringInHandshake) {
  23895. Server svr;
  23896. std::mutex mtx;
  23897. std::string received_target;
  23898. std::string received_token;
  23899. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23900. {
  23901. std::lock_guard<std::mutex> lock(mtx);
  23902. received_target = req.target;
  23903. if (req.has_param("token")) {
  23904. received_token = req.get_param_value("token");
  23905. }
  23906. }
  23907. std::string msg;
  23908. while (ws.read(msg)) {
  23909. ws.send(msg);
  23910. }
  23911. });
  23912. auto port = svr.bind_to_any_port("localhost");
  23913. std::thread t([&]() { svr.listen_after_bind(); });
  23914. svr.wait_until_ready();
  23915. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23916. "/ws?token=ABC&session=123");
  23917. ASSERT_TRUE(client.connect());
  23918. // Round-trip ensures the handler has run and captured the request.
  23919. ASSERT_TRUE(client.send("hello"));
  23920. std::string msg;
  23921. ASSERT_TRUE(client.read(msg));
  23922. EXPECT_EQ("hello", msg);
  23923. client.close();
  23924. {
  23925. std::lock_guard<std::mutex> lock(mtx);
  23926. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23927. EXPECT_EQ("ABC", received_token);
  23928. }
  23929. svr.stop();
  23930. t.join();
  23931. }
  23932. // Run a handshake against a throwaway server and hand the request the server
  23933. // received back to the caller, so tests can assert on the headers the client
  23934. // actually put on the wire.
  23935. static void capture_websocket_handshake_request(
  23936. const Headers &client_headers,
  23937. std::function<void(const Request &, int port)> verify) {
  23938. Server svr;
  23939. std::mutex mtx;
  23940. Request received;
  23941. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23942. {
  23943. std::lock_guard<std::mutex> lock(mtx);
  23944. received = req;
  23945. }
  23946. std::string msg;
  23947. while (ws.read(msg)) {
  23948. ws.send(msg);
  23949. }
  23950. });
  23951. auto port = svr.bind_to_any_port("localhost");
  23952. std::thread t([&]() { svr.listen_after_bind(); });
  23953. auto se = detail::scope_exit([&] {
  23954. svr.stop();
  23955. t.join();
  23956. });
  23957. svr.wait_until_ready();
  23958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23959. client_headers);
  23960. ASSERT_TRUE(client.connect());
  23961. ASSERT_TRUE(client.send("hello"));
  23962. std::string msg;
  23963. ASSERT_TRUE(client.read(msg));
  23964. client.close();
  23965. {
  23966. std::lock_guard<std::mutex> lock(mtx);
  23967. verify(received, port);
  23968. }
  23969. }
  23970. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23971. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23972. // Non-default port must be present in the Host header. Default ports
  23973. // (80/443) are omitted; that logic is covered by
  23974. // MakeHostAndPortStringTest.
  23975. EXPECT_EQ("localhost:" + std::to_string(port),
  23976. req.get_header_value("Host"));
  23977. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23978. req.get_header_value("User-Agent"));
  23979. EXPECT_FALSE(req.has_header("Accept"));
  23980. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23981. EXPECT_FALSE(req.has_header("Content-Length"));
  23982. });
  23983. }
  23984. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23985. capture_websocket_handshake_request(
  23986. {{"Host", "example.com"},
  23987. {"User-Agent", "custom-agent"},
  23988. {"X-Custom", "value"}},
  23989. [](const Request &req, int) {
  23990. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23991. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23992. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23993. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23994. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23995. });
  23996. }
  23997. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23998. capture_websocket_handshake_request(
  23999. {{"Upgrade", "bogus"},
  24000. {"Connection", "close"},
  24001. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24002. {"Sec-WebSocket-Version", "8"}},
  24003. [](const Request &req, int) {
  24004. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24005. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24006. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24007. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24008. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24009. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24010. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24011. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24012. req.get_header_value("Sec-WebSocket-Key"));
  24013. });
  24014. }
  24015. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24016. // A header the client refuses to send must abort the handshake before any
  24017. // part of it reaches the wire; a lone request line would otherwise sit in
  24018. // the peer's buffer as a truncated request.
  24019. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24020. ASSERT_NE(INVALID_SOCKET, srv);
  24021. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24022. sockaddr_in addr{};
  24023. addr.sin_family = AF_INET;
  24024. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24025. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24026. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24027. ASSERT_EQ(0, ::listen(srv, 1));
  24028. sockaddr_in bound{};
  24029. socklen_t bound_len = sizeof(bound);
  24030. ASSERT_EQ(
  24031. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24032. auto port = ntohs(bound.sin_port);
  24033. ssize_t received = -1;
  24034. std::thread t([&] {
  24035. // Bound every blocking call so a regression fails the test with a bad
  24036. // value instead of hanging the suite.
  24037. fd_set rfds;
  24038. FD_ZERO(&rfds);
  24039. FD_SET(srv, &rfds);
  24040. timeval tv{5, 0};
  24041. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24042. 0) {
  24043. return;
  24044. }
  24045. sockaddr_in cli_addr{};
  24046. socklen_t cli_len = sizeof(cli_addr);
  24047. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24048. if (cli == INVALID_SOCKET) { return; }
  24049. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24050. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24051. char buf[4096];
  24052. received = ::recv(cli, buf, sizeof(buf), 0);
  24053. });
  24054. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24055. // connect() has already shut the socket down by the time it returns false,
  24056. // so the peer sees EOF without waiting for the client to be destroyed.
  24057. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24058. {{"X-Bad", "a\r\nInjected: 1"}});
  24059. EXPECT_FALSE(client.connect());
  24060. t.join();
  24061. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24062. EXPECT_EQ(0, received);
  24063. }
  24064. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24065. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24066. // contains "upgrade" as a substring is a different token and must not
  24067. // start a WebSocket handshake.
  24068. auto make_request = [](const std::vector<std::string> &connection_values) {
  24069. Request req;
  24070. req.method = "GET";
  24071. req.headers.emplace("Upgrade", "websocket");
  24072. for (const auto &value : connection_values) {
  24073. req.headers.emplace("Connection", value);
  24074. }
  24075. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24076. req.headers.emplace("Sec-WebSocket-Version", "13");
  24077. return req;
  24078. };
  24079. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24080. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24081. EXPECT_TRUE(
  24082. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24083. EXPECT_TRUE(
  24084. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24085. EXPECT_TRUE(
  24086. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24087. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24088. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24089. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24090. EXPECT_FALSE(
  24091. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24092. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24093. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24094. }
  24095. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24096. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24097. // asks recipients to match each protocol-name case-insensitively, and RFC
  24098. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24099. // client naming websocket alongside another protocol, or on a second field
  24100. // line, is offering websocket; a value that merely contains "websocket" as a
  24101. // substring is a different protocol name and is not.
  24102. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24103. Request req;
  24104. req.method = "GET";
  24105. for (const auto &value : upgrade_values) {
  24106. req.headers.emplace("Upgrade", value);
  24107. }
  24108. req.headers.emplace("Connection", "Upgrade");
  24109. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24110. req.headers.emplace("Sec-WebSocket-Version", "13");
  24111. return req;
  24112. };
  24113. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24114. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24115. EXPECT_TRUE(
  24116. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24117. EXPECT_TRUE(
  24118. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24119. EXPECT_TRUE(
  24120. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24121. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24122. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24123. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24124. EXPECT_FALSE(
  24125. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24126. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24127. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24128. }
  24129. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24130. Server svr;
  24131. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24132. auto port = svr.bind_to_any_port("localhost");
  24133. std::thread t([&]() { svr.listen_after_bind(); });
  24134. auto se = detail::scope_exit([&] {
  24135. svr.stop();
  24136. t.join();
  24137. });
  24138. svr.wait_until_ready();
  24139. Headers headers = {{"Upgrade", "websocket"},
  24140. {"Connection", "notupgrade"},
  24141. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24142. {"Sec-WebSocket-Version", "13"}};
  24143. Client cli("localhost", port);
  24144. auto res = cli.Get("/ws", headers);
  24145. // The route exists only as a WebSocket route, so a request that fails the
  24146. // handshake check falls through to ordinary routing.
  24147. ASSERT_TRUE(res);
  24148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24149. }
  24150. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24151. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24152. // Connection value is the only thing left for the client to reject.
  24153. Server svr;
  24154. svr.Get("/ws", [](const Request &req, Response &res) {
  24155. res.status = StatusCode::SwitchingProtocol_101;
  24156. res.set_header("Upgrade", "websocket");
  24157. res.set_header("Connection", "notupgrade");
  24158. res.set_header("Sec-WebSocket-Accept",
  24159. detail::websocket_accept_key(
  24160. req.get_header_value("Sec-WebSocket-Key")));
  24161. });
  24162. auto port = svr.bind_to_any_port("localhost");
  24163. std::thread t([&]() { svr.listen_after_bind(); });
  24164. auto se = detail::scope_exit([&] {
  24165. svr.stop();
  24166. t.join();
  24167. });
  24168. svr.wait_until_ready();
  24169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24170. auto res = client.connect();
  24171. EXPECT_FALSE(res);
  24172. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24173. EXPECT_FALSE(client.is_open());
  24174. }
  24175. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24176. Server svr;
  24177. svr.Get("/ws", [](const Request &req, Response &res) {
  24178. res.status = StatusCode::SwitchingProtocol_101;
  24179. res.set_header("Upgrade", "websocket");
  24180. res.set_header("Connection", "Upgrade");
  24181. res.set_header("Sec-WebSocket-Accept",
  24182. detail::websocket_accept_key(
  24183. req.get_header_value("Sec-WebSocket-Key")));
  24184. res.set_header("Sec-WebSocket-Protocol", "admin");
  24185. });
  24186. auto port = svr.bind_to_any_port("localhost");
  24187. std::thread t([&]() { svr.listen_after_bind(); });
  24188. auto se = detail::scope_exit([&] {
  24189. svr.stop();
  24190. t.join();
  24191. });
  24192. svr.wait_until_ready();
  24193. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24194. // Server selects a subprotocol the client never offered
  24195. {
  24196. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24197. ws::WebSocketClient client(url, headers);
  24198. auto res = client.connect();
  24199. EXPECT_FALSE(res);
  24200. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24201. EXPECT_FALSE(client.is_open());
  24202. EXPECT_TRUE(client.subprotocol().empty());
  24203. }
  24204. // Client offered none but the server named one anyway
  24205. {
  24206. ws::WebSocketClient client(url);
  24207. auto res = client.connect();
  24208. EXPECT_FALSE(res);
  24209. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24210. EXPECT_FALSE(client.is_open());
  24211. EXPECT_TRUE(client.subprotocol().empty());
  24212. }
  24213. }
  24214. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24215. // The socket path doubles as the URL host, so it must not contain '/'.
  24216. const char *shard = getenv("GTEST_SHARD_INDEX");
  24217. const std::string sock_path =
  24218. shard ? std::string("httplib-ws-") + shard + ".sock"
  24219. : std::string("httplib-ws.sock");
  24220. std::remove(sock_path.c_str());
  24221. Server svr;
  24222. std::mutex mtx;
  24223. std::string received_host;
  24224. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24225. {
  24226. std::lock_guard<std::mutex> lock(mtx);
  24227. received_host = req.get_header_value("Host");
  24228. }
  24229. std::string msg;
  24230. while (ws.read(msg)) {
  24231. ws.send(msg);
  24232. }
  24233. });
  24234. svr.set_address_family(AF_UNIX);
  24235. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24236. auto se = detail::scope_exit([&] {
  24237. svr.stop();
  24238. t.join();
  24239. std::remove(sock_path.c_str());
  24240. });
  24241. svr.wait_until_ready();
  24242. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24243. client.set_address_family(AF_UNIX);
  24244. ASSERT_TRUE(client.connect());
  24245. ASSERT_TRUE(client.send("hello"));
  24246. std::string msg;
  24247. ASSERT_TRUE(client.read(msg));
  24248. client.close();
  24249. {
  24250. std::lock_guard<std::mutex> lock(mtx);
  24251. // There is no host:port for a Unix socket, so the same "localhost"
  24252. // placeholder the HTTP client uses is expected.
  24253. EXPECT_EQ("localhost", received_host);
  24254. }
  24255. }
  24256. // Two threads must never parse WebSocket frames from the same stream.
  24257. // close() used to read the peer's Close reply with its own frame read, so it
  24258. // raced a reader thread that was in the middle of a payload: the payload loop
  24259. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24260. // so bytes taken by close() were replaced with bytes from further along the
  24261. // stream. The message kept its length and silently changed content.
  24262. //
  24263. // The raw peer below sends a frame header plus part of the payload, waits for
  24264. // the handler to call close(), and only then sends the rest. Whichever thread
  24265. // would win the race for those bytes, the message must arrive intact, because
  24266. // close() must not touch the stream while read() owns it.
  24267. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24268. #ifndef _WIN32
  24269. signal(SIGPIPE, SIG_IGN);
  24270. #endif
  24271. const size_t payload_len = 120; // fits the 7-bit length field
  24272. const size_t prefix_len = 8;
  24273. const int attempts = 8;
  24274. std::string expected(payload_len, '\0');
  24275. for (size_t i = 0; i < payload_len; i++) {
  24276. expected[i] = static_cast<char>('a' + i % 26);
  24277. }
  24278. std::atomic<bool> peer_stalled{false};
  24279. std::atomic<bool> handler_done{false};
  24280. std::mutex received_mutex;
  24281. std::vector<std::string> received;
  24282. // Bound every wait, so a regression fails the test instead of hanging the
  24283. // suite.
  24284. auto wait_for = [](const std::atomic<bool> &flag) {
  24285. for (int i = 0; i < 500 && !flag; i++) {
  24286. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24287. }
  24288. };
  24289. Server svr;
  24290. svr.set_websocket_ping_interval(0);
  24291. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24292. std::thread reader([&]() {
  24293. std::string msg;
  24294. while (ws.read(msg)) {
  24295. std::lock_guard<std::mutex> guard(received_mutex);
  24296. received.push_back(msg);
  24297. }
  24298. });
  24299. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24300. // inside read_websocket_frame() when close() runs.
  24301. wait_for(peer_stalled);
  24302. ws.close();
  24303. reader.join();
  24304. handler_done = true;
  24305. });
  24306. auto port = svr.bind_to_any_port("127.0.0.1");
  24307. std::thread t([&]() { svr.listen_after_bind(); });
  24308. auto se = detail::scope_exit([&] {
  24309. svr.stop();
  24310. t.join();
  24311. });
  24312. svr.wait_until_ready();
  24313. auto send_bytes = [](socket_t s, const std::string &data) {
  24314. #ifdef _WIN32
  24315. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24316. #else
  24317. auto n = ::send(s, data.data(), data.size(), 0);
  24318. #endif
  24319. return n == static_cast<decltype(n)>(data.size());
  24320. };
  24321. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24322. // Every length used here fits the 7-bit length field.
  24323. auto masked_header = [](uint8_t first_byte, size_t len) {
  24324. std::string h;
  24325. h += static_cast<char>(first_byte);
  24326. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24327. h.append(4, '\0'); // mask key
  24328. return h;
  24329. };
  24330. for (int attempt = 0; attempt < attempts; attempt++) {
  24331. peer_stalled = false;
  24332. handler_done = false;
  24333. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24334. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24335. auto se_sock = detail::scope_exit([&] {
  24336. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24337. });
  24338. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24339. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24340. sockaddr_in addr{};
  24341. addr.sin_family = AF_INET;
  24342. addr.sin_port = htons(static_cast<uint16_t>(port));
  24343. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24344. ASSERT_EQ(
  24345. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24346. << "attempt " << attempt;
  24347. ASSERT_TRUE(send_bytes(sock,
  24348. "GET /ws HTTP/1.1\r\n"
  24349. "Host: 127.0.0.1\r\n"
  24350. "Upgrade: websocket\r\n"
  24351. "Connection: Upgrade\r\n"
  24352. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24353. "Sec-WebSocket-Version: 13\r\n"
  24354. "\r\n"))
  24355. << "attempt " << attempt;
  24356. std::string response;
  24357. while (response.find("\r\n\r\n") == std::string::npos) {
  24358. char buf[512];
  24359. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24360. if (n <= 0) { break; }
  24361. response.append(buf, static_cast<size_t>(n));
  24362. }
  24363. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24364. << "attempt " << attempt;
  24365. // Send the header of a Binary message but only the first prefix_len bytes
  24366. // of its payload, leaving the reader thread stalled inside the payload.
  24367. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24368. expected.substr(0, prefix_len)))
  24369. << "attempt " << attempt;
  24370. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24371. peer_stalled = true;
  24372. // Let close() send its Close frame and park in its own read before the
  24373. // rest of the payload arrives, so both threads are waiting for it.
  24374. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24375. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24376. close_frame += static_cast<char>(0x03); // status 1000
  24377. close_frame += static_cast<char>(0xE8);
  24378. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24379. << "attempt " << attempt;
  24380. // Closing the peer releases the reader thread even on the buggy path,
  24381. // where it waits for bytes another thread already consumed.
  24382. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24383. detail::close_socket(sock);
  24384. sock = INVALID_SOCKET;
  24385. wait_for(handler_done);
  24386. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24387. }
  24388. std::lock_guard<std::mutex> guard(received_mutex);
  24389. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24390. << "a message in flight when close() ran was dropped";
  24391. for (size_t i = 0; i < received.size(); i++) {
  24392. EXPECT_EQ(expected, received[i]) << "message " << i;
  24393. }
  24394. }
  24395. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24396. // returning the socket, or INVALID_SOCKET.
  24397. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24398. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24399. if (sock == INVALID_SOCKET) { return sock; }
  24400. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24401. sockaddr_in addr{};
  24402. addr.sin_family = AF_INET;
  24403. addr.sin_port = htons(static_cast<uint16_t>(port));
  24404. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24405. std::string req = "GET " + path +
  24406. " HTTP/1.1\r\n"
  24407. "Host: 127.0.0.1\r\n"
  24408. "Upgrade: websocket\r\n"
  24409. "Connection: Upgrade\r\n"
  24410. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24411. "Sec-WebSocket-Version: 13\r\n"
  24412. "\r\n";
  24413. std::string res;
  24414. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24415. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24416. static_cast<ssize_t>(req.size())) {
  24417. char c;
  24418. while (res.find("\r\n\r\n") == std::string::npos &&
  24419. ::recv(sock, &c, 1, 0) == 1) {
  24420. res += c;
  24421. }
  24422. }
  24423. if (res.find(" 101 ") == std::string::npos) {
  24424. detail::close_socket(sock);
  24425. return INVALID_SOCKET;
  24426. }
  24427. return sock;
  24428. }
  24429. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24430. // The payload must fit the 7-bit length field.
  24431. static std::string masked_frame(uint8_t first_byte,
  24432. const std::string &payload) {
  24433. std::string f;
  24434. f += static_cast<char>(first_byte);
  24435. f += static_cast<char>(0x80 | payload.size());
  24436. f.append(4, '\0');
  24437. return f + payload;
  24438. }
  24439. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24440. std::atomic<bool> done{false};
  24441. std::string received;
  24442. Server svr;
  24443. svr.set_websocket_ping_interval(0);
  24444. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24445. std::string msg;
  24446. if (ws.read(msg) == ws::Binary) { received = msg; }
  24447. done = true;
  24448. });
  24449. auto port = svr.bind_to_any_port("127.0.0.1");
  24450. std::thread t([&]() { svr.listen_after_bind(); });
  24451. auto se = detail::scope_exit([&] {
  24452. svr.stop();
  24453. t.join();
  24454. });
  24455. svr.wait_until_ready();
  24456. auto sock = connect_raw_websocket(port, "/ws");
  24457. ASSERT_NE(INVALID_SOCKET, sock);
  24458. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24459. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24460. masked_frame(0x89, "p") + // FIN + Ping
  24461. masked_frame(0x80, "lo"); // FIN + Continuation
  24462. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24463. for (int i = 0; i < 500 && !done; i++) {
  24464. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24465. }
  24466. ASSERT_TRUE(done);
  24467. EXPECT_EQ("Hello", received);
  24468. // The Ping between the fragments is answered with a Pong.
  24469. char pong[3];
  24470. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24471. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24472. }
  24473. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24474. Server svr;
  24475. svr.set_websocket_ping_interval(-1);
  24476. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24477. std::string msg;
  24478. while (ws.read(msg)) {}
  24479. });
  24480. auto port = svr.bind_to_any_port("127.0.0.1");
  24481. std::thread t([&]() { svr.listen_after_bind(); });
  24482. auto se = detail::scope_exit([&] {
  24483. svr.stop();
  24484. t.join();
  24485. });
  24486. svr.wait_until_ready();
  24487. auto sock = connect_raw_websocket(port, "/ws");
  24488. ASSERT_NE(INVALID_SOCKET, sock);
  24489. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24490. // Nothing comes while the client stays quiet.
  24491. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24492. char c;
  24493. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24494. }
  24495. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24496. // and that has to end a read() already waiting on the peer, on every platform.
  24497. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24498. // The peer sends no pings, and its handler never calls read(), which is
  24499. // where pongs are written.
  24500. std::mutex mutex;
  24501. std::condition_variable cv;
  24502. auto release = false;
  24503. svr.set_websocket_ping_interval(0);
  24504. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24505. std::unique_lock<std::mutex> lock(mutex);
  24506. cv.wait(lock, [&] { return release; });
  24507. });
  24508. auto port = svr.bind_to_any_port(HOST);
  24509. std::thread t([&]() { svr.listen_after_bind(); });
  24510. auto se = detail::scope_exit([&] {
  24511. {
  24512. std::lock_guard<std::mutex> lock(mutex);
  24513. release = true;
  24514. }
  24515. cv.notify_all();
  24516. svr.stop();
  24517. t.join();
  24518. });
  24519. svr.wait_until_ready();
  24520. ws::WebSocketClient client(std::string(scheme) +
  24521. "://localhost:" + std::to_string(port) + "/ws");
  24522. #ifdef CPPHTTPLIB_SSL_ENABLED
  24523. client.enable_server_certificate_verification(false);
  24524. #endif
  24525. // A ping a second, given up on after two go unanswered: about 3s
  24526. client.set_websocket_ping_interval(1);
  24527. client.set_websocket_max_missed_pongs(2);
  24528. // Well past that, so that a read the timeout ends instead stands out
  24529. client.set_read_timeout(10);
  24530. ASSERT_TRUE(client.connect());
  24531. auto start = std::chrono::steady_clock::now();
  24532. std::string msg;
  24533. EXPECT_EQ(ws::Fail, client.read(msg));
  24534. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24535. std::chrono::steady_clock::now() - start)
  24536. .count(),
  24537. 6000);
  24538. EXPECT_FALSE(client.is_open());
  24539. }
  24540. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24541. Server svr;
  24542. check_pong_timeout_ends_read(svr, "ws");
  24543. }
  24544. #ifdef CPPHTTPLIB_SSL_ENABLED
  24545. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24547. ASSERT_TRUE(svr.is_valid());
  24548. check_pong_timeout_ends_read(svr, "wss");
  24549. }
  24550. #endif
  24551. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24552. Server svr;
  24553. svr.set_websocket_ping_interval(0);
  24554. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24555. std::string msg;
  24556. while (ws.read(msg)) {}
  24557. });
  24558. auto port = svr.bind_to_any_port("127.0.0.1");
  24559. std::thread t([&]() { svr.listen_after_bind(); });
  24560. auto se = detail::scope_exit([&] {
  24561. svr.stop();
  24562. t.join();
  24563. });
  24564. svr.wait_until_ready();
  24565. // Each Close payload and the reply it should get: an echo when valid, 1002
  24566. // otherwise.
  24567. std::vector<std::pair<std::string, std::string>> cases = {
  24568. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24569. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24570. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24571. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24572. };
  24573. // Also between the fragments of a message.
  24574. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24575. for (const auto &c : cases) {
  24576. auto sock = connect_raw_websocket(port, "/ws");
  24577. ASSERT_NE(INVALID_SOCKET, sock);
  24578. auto frames = prefix + masked_frame(0x88, c.first);
  24579. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24580. std::string reply;
  24581. char buf[256];
  24582. while (reply.size() < 2 + c.second.size()) {
  24583. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24584. if (n <= 0) { break; }
  24585. reply.append(buf, static_cast<size_t>(n));
  24586. }
  24587. detail::close_socket(sock);
  24588. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24589. c.second,
  24590. reply);
  24591. }
  24592. }
  24593. }
  24594. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24595. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24596. protected:
  24597. void SetUp() override {
  24598. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24599. SERVER_PRIVATE_KEY_FILE);
  24600. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24601. std::string msg;
  24602. ws::ReadResult ret;
  24603. while ((ret = ws.read(msg))) {
  24604. if (ret == ws::Binary) {
  24605. ws.send(msg.data(), msg.size());
  24606. } else {
  24607. ws.send(msg);
  24608. }
  24609. }
  24610. });
  24611. port_ = server_->bind_to_any_port(HOST);
  24612. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24613. server_->wait_until_ready();
  24614. }
  24615. void TearDown() override {
  24616. server_->stop();
  24617. if (server_thread_.joinable()) { server_thread_.join(); }
  24618. }
  24619. std::unique_ptr<SSLServer> server_;
  24620. std::thread server_thread_;
  24621. int port_ = 0;
  24622. };
  24623. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24624. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24625. {
  24626. ws::WebSocketClient client(url);
  24627. client.enable_server_certificate_verification(false);
  24628. auto calls = 0;
  24629. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24630. calls++;
  24631. return false;
  24632. });
  24633. EXPECT_FALSE(client.connect());
  24634. EXPECT_GT(calls, 0);
  24635. }
  24636. {
  24637. ws::WebSocketClient client(url);
  24638. client.enable_server_certificate_verification(false);
  24639. client.set_session_verifier([](tls::session_t) {
  24640. return SSLVerifierResponse::CertificateRejected;
  24641. });
  24642. EXPECT_FALSE(client.connect());
  24643. }
  24644. {
  24645. ws::WebSocketClient client(url);
  24646. client.enable_server_certificate_verification(false);
  24647. client.set_session_verifier([](tls::session_t) {
  24648. return SSLVerifierResponse::CertificateAccepted;
  24649. });
  24650. EXPECT_TRUE(client.connect());
  24651. }
  24652. }
  24653. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24654. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24655. "/ws-echo");
  24656. client.enable_server_certificate_verification(false);
  24657. ASSERT_TRUE(client.connect());
  24658. ASSERT_TRUE(client.is_open());
  24659. ASSERT_TRUE(client.send("Hello WSS"));
  24660. std::string msg;
  24661. EXPECT_EQ(ws::Text, client.read(msg));
  24662. EXPECT_EQ("Hello WSS", msg);
  24663. client.close();
  24664. }
  24665. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24666. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24667. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24668. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24669. // client (without calling close() first) is the only path that runs
  24670. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24671. // bug exactly.
  24672. //
  24673. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24674. // when linked against an instrumented libssl; run under Valgrind to catch it
  24675. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24676. // suite (the freed session otherwise stalls on the close handshake) — this test
  24677. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24678. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24679. {
  24680. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24681. "/ws-echo");
  24682. client.enable_server_certificate_verification(false);
  24683. client.set_read_timeout(2, 0);
  24684. client.set_write_timeout(2, 0);
  24685. ASSERT_TRUE(client.connect());
  24686. ASSERT_TRUE(client.is_open());
  24687. ASSERT_TRUE(client.send("still open"));
  24688. // Intentionally do NOT call client.close(): leaving scope runs
  24689. // shutdown_and_close() with the WebSocket still open, which must send the
  24690. // close frame while the TLS session is still alive.
  24691. }
  24692. }
  24693. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24694. // shutdown_and_close() at the start of connect(), reproducing the same
  24695. // use-after-free within the test body rather than at scope exit. The second
  24696. // connect must succeed and echo, proving the close handshake ran over a live
  24697. // session. See the note above about memory-tool requirements.
  24698. TEST_F(WebSocketSSLIntegrationTest,
  24699. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24700. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24701. "/ws-echo");
  24702. client.enable_server_certificate_verification(false);
  24703. client.set_read_timeout(2, 0);
  24704. client.set_write_timeout(2, 0);
  24705. ASSERT_TRUE(client.connect());
  24706. ASSERT_TRUE(client.is_open());
  24707. ASSERT_TRUE(client.send("still open"));
  24708. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24709. // the still-open connection, which must not touch a freed TLS session.
  24710. ASSERT_TRUE(client.connect());
  24711. ASSERT_TRUE(client.is_open());
  24712. ASSERT_TRUE(client.send("after reconnect"));
  24713. std::string msg;
  24714. EXPECT_EQ(ws::Text, client.read(msg));
  24715. EXPECT_EQ("after reconnect", msg);
  24716. client.close();
  24717. }
  24718. #endif
  24719. #ifdef CPPHTTPLIB_SSL_ENABLED
  24720. class WebSocketSSLCATest : public ::testing::Test {
  24721. protected:
  24722. void SetUp() override {
  24723. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24724. SERVER_PRIVATE_KEY_FILE);
  24725. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24726. std::string msg;
  24727. while (ws.read(msg)) {
  24728. ws.send(msg);
  24729. }
  24730. });
  24731. port_ = server_->bind_to_any_port("127.0.0.1");
  24732. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24733. server_->wait_until_ready();
  24734. }
  24735. void TearDown() override {
  24736. server_->stop();
  24737. if (server_thread_.joinable()) { server_thread_.join(); }
  24738. }
  24739. std::string url() const {
  24740. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24741. }
  24742. std::unique_ptr<SSLServer> server_;
  24743. std::thread server_thread_;
  24744. int port_ = 0;
  24745. };
  24746. // A custom CA loaded as PEM verifies the server with full certificate
  24747. // verification enabled
  24748. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24749. ws::WebSocketClient client(url());
  24750. std::string cert;
  24751. read_file(SERVER_CERT2_FILE, cert);
  24752. client.load_ca_cert_store(cert.c_str(), cert.size());
  24753. ASSERT_TRUE(client.connect());
  24754. ASSERT_TRUE(client.send("hello"));
  24755. std::string msg;
  24756. EXPECT_EQ(ws::Text, client.read(msg));
  24757. EXPECT_EQ("hello", msg);
  24758. client.close();
  24759. }
  24760. // A custom CA that does not cover the server must fail verification (the
  24761. // custom CA is exclusive; system certs are not loaded alongside it)
  24762. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24763. ws::WebSocketClient client(url());
  24764. std::string cert;
  24765. read_file(CLIENT_CA_CERT_FILE, cert);
  24766. client.load_ca_cert_store(cert.c_str(), cert.size());
  24767. auto res = client.connect();
  24768. ASSERT_FALSE(res);
  24769. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24770. EXPECT_EQ(-1, res.status());
  24771. EXPECT_NE(0u, res.ssl_backend_error());
  24772. }
  24773. // The same CA as a file path rather than PEM in memory
  24774. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24775. ws::WebSocketClient client(url());
  24776. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24777. ASSERT_TRUE(client.connect());
  24778. ASSERT_TRUE(client.send("hello"));
  24779. std::string msg;
  24780. EXPECT_EQ(ws::Text, client.read(msg));
  24781. EXPECT_EQ("hello", msg);
  24782. client.close();
  24783. }
  24784. // ...and a CA file that does not cover the server still fails, so it is the
  24785. // path above that decides the outcome
  24786. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24787. ws::WebSocketClient client(url());
  24788. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24789. ASSERT_FALSE(client.connect());
  24790. }
  24791. // Regression test: reconnecting with a native custom CA store used to reuse
  24792. // a store handle the previous TLS context had already freed (use-after-free
  24793. // under the OpenSSL backend). The context now lives as long as the client.
  24794. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24795. ws::WebSocketClient client(url());
  24796. std::string cert;
  24797. read_file(SERVER_CERT2_FILE, cert);
  24798. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24799. ASSERT_TRUE(client.connect());
  24800. client.close();
  24801. ASSERT_TRUE(client.connect());
  24802. ASSERT_TRUE(client.send("again"));
  24803. std::string msg;
  24804. EXPECT_EQ(ws::Text, client.read(msg));
  24805. EXPECT_EQ("again", msg);
  24806. client.close();
  24807. }
  24808. // Regression test: a certificate with a trusted chain but no identity match
  24809. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24810. // verification entirely for IP hosts, so this connection succeeded there.
  24811. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24812. // chain verification while the identity check must still fail.
  24813. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24815. ASSERT_TRUE(svr.is_valid());
  24816. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24817. std::string msg;
  24818. while (ws.read(msg)) {
  24819. ws.send(msg);
  24820. }
  24821. });
  24822. auto port = svr.bind_to_any_port("127.0.0.1");
  24823. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24824. auto se = detail::scope_exit([&] {
  24825. svr.stop();
  24826. t.join();
  24827. });
  24828. svr.wait_until_ready();
  24829. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24830. "/echo");
  24831. std::string cert;
  24832. read_file(SERVER_CERT_FILE, cert);
  24833. client.load_ca_cert_store(cert.c_str(), cert.size());
  24834. ASSERT_FALSE(client.connect());
  24835. }
  24836. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24837. // SNI, so nothing binds the host name to the TLS session. These bind the
  24838. // server to "localhost" instead, the only shape that exercises the SNI and
  24839. // hostname-verification path with certificate verification left enabled.
  24840. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24841. protected:
  24842. void Start(const char *cert_file) {
  24843. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24844. SERVER_PRIVATE_KEY_FILE);
  24845. ASSERT_TRUE(server_->is_valid());
  24846. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24847. std::string msg;
  24848. while (ws.read(msg)) {
  24849. ws.send(msg);
  24850. }
  24851. });
  24852. port_ = server_->bind_to_any_port("localhost");
  24853. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24854. server_->wait_until_ready();
  24855. }
  24856. void TearDown() override {
  24857. if (server_) { server_->stop(); }
  24858. if (server_thread_.joinable()) { server_thread_.join(); }
  24859. }
  24860. std::string url() const {
  24861. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24862. }
  24863. std::unique_ptr<SSLServer> server_;
  24864. std::thread server_thread_;
  24865. int port_ = 0;
  24866. };
  24867. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24868. // out and the connection is usable
  24869. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24870. Start(SERVER_CERT2_FILE);
  24871. ws::WebSocketClient client(url());
  24872. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24873. ASSERT_TRUE(client.connect());
  24874. ASSERT_TRUE(client.send("hello"));
  24875. std::string msg;
  24876. EXPECT_EQ(ws::Text, client.read(msg));
  24877. EXPECT_EQ("hello", msg);
  24878. client.close();
  24879. }
  24880. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24881. // while the identity check must still reject "localhost"
  24882. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24883. Start(SERVER_CERT_FILE);
  24884. ws::WebSocketClient client(url());
  24885. client.set_ca_cert_path(SERVER_CERT_FILE);
  24886. auto res = client.connect();
  24887. ASSERT_FALSE(res);
  24888. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24889. EXPECT_EQ(-1, res.status());
  24890. }
  24891. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24892. // disabled: the chain is still checked, only the identity check is skipped
  24893. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24894. Start(SERVER_CERT_FILE);
  24895. ws::WebSocketClient client(url());
  24896. client.set_ca_cert_path(SERVER_CERT_FILE);
  24897. client.enable_server_hostname_verification(false);
  24898. ASSERT_TRUE(client.connect());
  24899. ASSERT_TRUE(client.send("hello"));
  24900. std::string msg;
  24901. EXPECT_EQ(ws::Text, client.read(msg));
  24902. EXPECT_EQ("hello", msg);
  24903. client.close();
  24904. }
  24905. // A CA that did not sign the server certificate fails the chain, even though
  24906. // the name would match
  24907. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24908. Start(SERVER_CERT2_FILE);
  24909. ws::WebSocketClient client(url());
  24910. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24911. ASSERT_FALSE(client.connect());
  24912. }
  24913. // With verification disabled, neither the chain nor the name is checked
  24914. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24915. Start(SERVER_CERT_FILE);
  24916. ws::WebSocketClient client(url());
  24917. client.enable_server_certificate_verification(false);
  24918. ASSERT_TRUE(client.connect());
  24919. ASSERT_TRUE(client.send("hello"));
  24920. std::string msg;
  24921. EXPECT_EQ(ws::Text, client.read(msg));
  24922. EXPECT_EQ("hello", msg);
  24923. client.close();
  24924. }
  24925. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24926. protected:
  24927. void SetUp() override {
  24928. server_ = httplib::detail::make_unique<SSLServer>(
  24929. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24930. ASSERT_TRUE(server_->is_valid());
  24931. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24932. std::string msg;
  24933. while (ws.read(msg)) {
  24934. ws.send(msg);
  24935. }
  24936. });
  24937. port_ = server_->bind_to_any_port("localhost");
  24938. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24939. server_->wait_until_ready();
  24940. }
  24941. void TearDown() override {
  24942. server_->stop();
  24943. if (server_thread_.joinable()) { server_thread_.join(); }
  24944. }
  24945. std::string url() const {
  24946. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24947. }
  24948. void ConnectWithClientCert(const std::string &client_cert_file,
  24949. const std::string &client_private_key_file,
  24950. const char *private_key_password) {
  24951. std::string cert_pem, key_pem;
  24952. read_file(client_cert_file, cert_pem);
  24953. read_file(client_private_key_file, key_pem);
  24954. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24955. key_pem.c_str(), key_pem.size(),
  24956. private_key_password};
  24957. ConnectWithPem(pem);
  24958. }
  24959. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24960. ws::WebSocketClient client(url(), pem);
  24961. ASSERT_TRUE(client.is_valid());
  24962. client.enable_server_certificate_verification(false);
  24963. ASSERT_TRUE(client.connect());
  24964. ASSERT_TRUE(client.send("hello"));
  24965. std::string msg;
  24966. EXPECT_EQ(ws::Text, client.read(msg));
  24967. EXPECT_EQ("hello", msg);
  24968. client.close();
  24969. }
  24970. std::unique_ptr<SSLServer> server_;
  24971. std::thread server_thread_;
  24972. int port_ = 0;
  24973. };
  24974. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24975. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24976. }
  24977. // Control for the tests above: the fixture's server really does require a
  24978. // client certificate, so it is the PEM the constructor installed that decides
  24979. // the outcome.
  24980. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24981. ws::WebSocketClient client(url());
  24982. ASSERT_TRUE(client.is_valid());
  24983. client.enable_server_certificate_verification(false);
  24984. EXPECT_FALSE(client.connect());
  24985. }
  24986. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24987. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24988. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24989. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24990. }
  24991. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24992. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24993. std::string cert_pem, key_pem;
  24994. read_file(CLIENT_CERT_FILE, cert_pem);
  24995. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24996. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24997. std::vector<char> key(key_pem.begin(), key_pem.end());
  24998. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24999. key.size(), nullptr};
  25000. ConnectWithPem(pem);
  25001. }
  25002. #endif
  25003. #if !defined(_WIN32)
  25004. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25005. auto secret_dir = std::string("./symlink_test_secret");
  25006. auto served_dir = std::string("./symlink_test_served");
  25007. auto secret_file = secret_dir + "/secret.txt";
  25008. auto symlink_path = served_dir + "/escape";
  25009. // Setup: create directories and files
  25010. mkdir(secret_dir.c_str(), 0755);
  25011. mkdir(served_dir.c_str(), 0755);
  25012. {
  25013. std::ofstream ofs(secret_file);
  25014. ofs << "SECRET_DATA";
  25015. }
  25016. // Create symlink using absolute path so it resolves correctly
  25017. #ifdef PATH_MAX
  25018. char abs_secret[PATH_MAX];
  25019. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25020. #else
  25021. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25022. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25023. ASSERT_NE(nullptr, abs_secret);
  25024. #endif
  25025. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25026. auto se = detail::scope_exit([&] {
  25027. unlink(symlink_path.c_str());
  25028. unlink(secret_file.c_str());
  25029. rmdir(served_dir.c_str());
  25030. rmdir(secret_dir.c_str());
  25031. });
  25032. Server svr;
  25033. svr.set_mount_point("/", served_dir);
  25034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25035. auto se2 = detail::scope_exit([&] {
  25036. svr.stop();
  25037. listen_thread.join();
  25038. });
  25039. svr.wait_until_ready();
  25040. Client cli("localhost", PORT);
  25041. // Symlink pointing outside base dir should be blocked
  25042. auto res = cli.Get("/escape/secret.txt");
  25043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25044. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25045. }
  25046. #endif
  25047. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25048. // "GET /smuggled" request), reads the first response, and only then sends the
  25049. // embedded request as the body. Returns how many times /smuggled ran.
  25050. //
  25051. // The body is sent AFTER receiving the first response (as in the original
  25052. // PoC) so that the stream_line_reader cannot buffer it together with the
  25053. // headers of the first request.
  25054. static int count_smuggled_requests(const std::string &outer_head,
  25055. std::string &first_response) {
  25056. Server svr;
  25057. svr.set_mount_point("/", "./www");
  25058. std::atomic<int> smuggled_count(0);
  25059. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25060. smuggled_count++;
  25061. res.set_content("oops", "text/plain");
  25062. });
  25063. svr.Post("/post", [&](const Request &req, Response &res) {
  25064. res.set_content(req.body, "text/plain");
  25065. });
  25066. auto port = svr.bind_to_any_port("localhost");
  25067. thread t = thread([&] { svr.listen_after_bind(); });
  25068. auto se = detail::scope_exit([&] {
  25069. svr.stop();
  25070. t.join();
  25071. });
  25072. svr.wait_until_ready();
  25073. auto error = Error::Success;
  25074. auto sock = detail::create_client_socket(
  25075. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25076. /*connection_timeout_sec=*/2, 0,
  25077. /*read_timeout_sec=*/2, 0,
  25078. /*write_timeout_sec=*/2, 0, std::string(), error);
  25079. EXPECT_NE(INVALID_SOCKET, sock);
  25080. if (sock == INVALID_SOCKET) { return -1; }
  25081. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25082. // The "smuggled" request will be sent as the body of the outer request
  25083. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25084. "Host: localhost\r\n"
  25085. "Connection: close\r\n"
  25086. "\r\n";
  25087. auto head = outer_head;
  25088. auto len = std::to_string(smuggled.size());
  25089. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25090. pos = head.find("{len}", pos + len.size())) {
  25091. head.replace(pos, 5, len);
  25092. }
  25093. // Step 1: Send only the outer request headers (no body yet)
  25094. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25095. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25096. // Step 2: Read the first response
  25097. char buf[4096];
  25098. for (;;) {
  25099. auto n = recv(sock, buf, sizeof(buf), 0);
  25100. if (n <= 0) break;
  25101. first_response.append(buf, static_cast<size_t>(n));
  25102. // Stop once we have a complete response (headers + body)
  25103. auto hdr_end = first_response.find("\r\n\r\n");
  25104. if (hdr_end != std::string::npos) {
  25105. // Check for Content-Length to know when the body is complete
  25106. auto cl_pos = first_response.find("Content-Length:");
  25107. if (cl_pos != std::string::npos) {
  25108. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25109. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25110. auto cl = std::stoul(
  25111. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25112. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25113. } else {
  25114. break; // No Content-Length, assume headers-only response
  25115. }
  25116. }
  25117. }
  25118. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25119. // vulnerable server the keep-alive loop reads this as a second request. The
  25120. // server may already have closed the connection, so the result is ignored.
  25121. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25122. // Half-close so that a server which drained the body sees EOF and closes,
  25123. // instead of the read below waiting for the read timeout.
  25124. #ifdef _WIN32
  25125. ::shutdown(sock, SD_SEND);
  25126. #else
  25127. ::shutdown(sock, SHUT_WR);
  25128. #endif
  25129. // Step 4: Read until the server closes the connection
  25130. for (;;) {
  25131. auto n = recv(sock, buf, sizeof(buf), 0);
  25132. if (n <= 0) break;
  25133. }
  25134. return smuggled_count.load();
  25135. }
  25136. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25137. // A GET request with Content-Length to a static file handler must have its
  25138. // body drained before the keep-alive connection is reused. Otherwise the
  25139. // unread body bytes are interpreted as the next HTTP request.
  25140. std::string first_response;
  25141. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25142. "Host: localhost\r\n"
  25143. "Content-Length: {len}\r\n"
  25144. "\r\n",
  25145. first_response));
  25146. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25147. }
  25148. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25149. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25150. // be answered with 400 and the connection closed. Treating it as "no body"
  25151. // leaves the body to be parsed as the next request.
  25152. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25153. const char *targets[] = {
  25154. "GET /file", // handler that never reads the body
  25155. "GET /not-found", // no handler matches (404)
  25156. "POST /post", // handler that reads the body
  25157. };
  25158. for (auto target : targets) {
  25159. for (auto value : values) {
  25160. std::string first_response;
  25161. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25162. " HTTP/1.1\r\n"
  25163. "Host: localhost\r\n"
  25164. "Content-Length: " +
  25165. value + "\r\n\r\n",
  25166. first_response))
  25167. << target << " with Content-Length: " << value;
  25168. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25169. << target << " with Content-Length: " << value;
  25170. }
  25171. }
  25172. }
  25173. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25174. // A 400 for an unparseable request line leaves the rest of the message
  25175. // unread, so the connection must be closed rather than reused.
  25176. std::string first_response;
  25177. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25178. "Host: localhost\r\n"
  25179. "Content-Length: {len}\r\n"
  25180. "\r\n",
  25181. first_response));
  25182. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25183. }
  25184. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25185. // Same as above for a header block that fails to parse.
  25186. std::string first_response;
  25187. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25188. "Host: localhost\r\n"
  25189. "Bad Header\r\n"
  25190. "Content-Length: {len}\r\n"
  25191. "\r\n",
  25192. first_response));
  25193. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25194. }
  25195. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25196. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25197. // server must not read another request on that connection, even when the
  25198. // request had no body to drain.
  25199. std::string first_response;
  25200. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25201. "Host: localhost\r\n"
  25202. "\r\n",
  25203. first_response));
  25204. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25205. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25206. }
  25207. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25208. // A content reader that stops early leaves the stream inside the body.
  25209. // Draining the whole Content-Length from there, or reading the body again,
  25210. // reads into the next request, and whatever follows is parsed as a request
  25211. // of its own.
  25212. Server svr;
  25213. std::atomic<int> smuggled_count(0);
  25214. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25215. svr.Post("/upload", [](const Request &req, Response &res,
  25216. const ContentReader &content_reader) {
  25217. // Stop at the last chunk, so the whole body has been read however it
  25218. // arrives.
  25219. auto length = req.get_header_value_u64("Content-Length");
  25220. size_t total = 0;
  25221. auto consumed = content_reader([&](const char *, size_t n) {
  25222. total += n;
  25223. return total < length;
  25224. });
  25225. EXPECT_FALSE(consumed);
  25226. if (req.has_param("retry")) {
  25227. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25228. }
  25229. // Replace the 400 the aborted read set, which would close the connection.
  25230. res.set_redirect("/done");
  25231. });
  25232. auto port = svr.bind_to_any_port(HOST);
  25233. thread t = thread([&] { svr.listen_after_bind(); });
  25234. auto se = detail::scope_exit([&] {
  25235. svr.stop();
  25236. t.join();
  25237. });
  25238. svr.wait_until_ready();
  25239. // A front end sees the second request as a POST whose body is the GET. The
  25240. // first body is as long as the POST's headers, so draining it again reads
  25241. // exactly those and leaves the GET to be parsed next.
  25242. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25243. "Host: localhost\r\n"
  25244. "\r\n";
  25245. std::string second_head = "POST /post HTTP/1.1\r\n"
  25246. "Host: localhost\r\n"
  25247. "Content-Length: " +
  25248. std::to_string(inner.size()) +
  25249. "\r\n"
  25250. "\r\n";
  25251. for (auto target : {"/upload", "/upload?retry"}) {
  25252. smuggled_count = 0;
  25253. std::string request = "POST " + std::string(target) +
  25254. " HTTP/1.1\r\n"
  25255. "Host: localhost\r\n"
  25256. "Content-Length: " +
  25257. std::to_string(second_head.size()) +
  25258. "\r\n"
  25259. "\r\n" +
  25260. std::string(second_head.size(), 'A') + second_head +
  25261. inner;
  25262. std::string response;
  25263. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25264. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25265. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25266. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25267. EXPECT_EQ(0, smuggled_count.load()) << target;
  25268. }
  25269. }
  25270. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25271. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25272. // must be rejected with 400 Bad Request.
  25273. Server svr;
  25274. svr.Post("/test", [&](const Request &, Response &res) {
  25275. res.set_content("ok", "text/plain");
  25276. });
  25277. thread t = thread([&] { svr.listen(HOST, PORT); });
  25278. auto se = detail::scope_exit([&] {
  25279. svr.stop();
  25280. t.join();
  25281. ASSERT_FALSE(svr.is_running());
  25282. });
  25283. svr.wait_until_ready();
  25284. // Exact "chunked"
  25285. {
  25286. auto req = "POST /test HTTP/1.1\r\n"
  25287. "Host: localhost\r\n"
  25288. "Content-Length: 5\r\n"
  25289. "Transfer-Encoding: chunked\r\n"
  25290. "Connection: close\r\n"
  25291. "\r\n"
  25292. "hello";
  25293. std::string response;
  25294. ASSERT_TRUE(send_request(1, req, &response));
  25295. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25296. response.substr(0, response.find("\r\n")));
  25297. }
  25298. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25299. {
  25300. auto req = "POST /test HTTP/1.1\r\n"
  25301. "Host: localhost\r\n"
  25302. "Content-Length: 5\r\n"
  25303. "Transfer-Encoding: gzip, chunked\r\n"
  25304. "Connection: close\r\n"
  25305. "\r\n"
  25306. "hello";
  25307. std::string response;
  25308. ASSERT_TRUE(send_request(1, req, &response));
  25309. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25310. response.substr(0, response.find("\r\n")));
  25311. }
  25312. }
  25313. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25314. Server svr;
  25315. svr.Post("/test", [&](const Request &, Response &res) {
  25316. res.set_content("ok", "text/plain");
  25317. });
  25318. thread t = thread([&] { svr.listen(HOST, PORT); });
  25319. auto se = detail::scope_exit([&] {
  25320. svr.stop();
  25321. t.join();
  25322. ASSERT_FALSE(svr.is_running());
  25323. });
  25324. svr.wait_until_ready();
  25325. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25326. // length cannot be determined, so the server must answer 400 and close
  25327. // rather than treat the request as bodyless and leave the body in the
  25328. // socket for the next request to pick up.
  25329. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25330. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25331. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25332. std::string response;
  25333. ASSERT_TRUE(send_request(1, req, &response));
  25334. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25335. response.substr(0, response.find("\r\n")))
  25336. << transfer_encoding;
  25337. }
  25338. // RFC 9110 5.3: the codings may also be split across several
  25339. // Transfer-Encoding lines, which combine in the order they were received.
  25340. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25341. // just like the single-line "chunked, gzip" above.
  25342. {
  25343. auto req = "POST /test HTTP/1.1\r\n"
  25344. "Host: localhost\r\n"
  25345. "Transfer-Encoding: chunked\r\n"
  25346. "Transfer-Encoding: gzip\r\n"
  25347. "\r\n"
  25348. "0\r\n\r\n";
  25349. std::string response;
  25350. ASSERT_TRUE(send_request(1, req, &response));
  25351. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25352. response.substr(0, response.find("\r\n")));
  25353. }
  25354. // A sequence ending in chunked stays valid.
  25355. auto req = "POST /test HTTP/1.1\r\n"
  25356. "Host: localhost\r\n"
  25357. "Transfer-Encoding: gzip, chunked\r\n"
  25358. "Connection: close\r\n"
  25359. "\r\n"
  25360. "0\r\n\r\n";
  25361. std::string response;
  25362. ASSERT_TRUE(send_request(1, req, &response));
  25363. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25364. // ...including when it is spread over several lines.
  25365. auto split_req = "POST /test HTTP/1.1\r\n"
  25366. "Host: localhost\r\n"
  25367. "Transfer-Encoding: gzip\r\n"
  25368. "Transfer-Encoding: chunked\r\n"
  25369. "Connection: close\r\n"
  25370. "\r\n"
  25371. "0\r\n\r\n";
  25372. std::string split_response;
  25373. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25374. EXPECT_EQ("HTTP/1.1 200 OK",
  25375. split_response.substr(0, split_response.find("\r\n")));
  25376. }
  25377. // Regression for issue #2450: a DELETE without Content-Length on a
  25378. // keep-alive connection must not let the post-response drain consume the
  25379. // next request's bytes.
  25380. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25381. Server svr;
  25382. std::atomic<int> delete_count(0);
  25383. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25384. delete_count++;
  25385. res.status = StatusCode::NoContent_204;
  25386. });
  25387. auto port = svr.bind_to_any_port(HOST);
  25388. thread t = thread([&] { svr.listen_after_bind(); });
  25389. auto se = detail::scope_exit([&] {
  25390. svr.stop();
  25391. t.join();
  25392. });
  25393. svr.wait_until_ready();
  25394. auto error = Error::Success;
  25395. auto sock = detail::create_client_socket(
  25396. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25397. /*connection_timeout_sec=*/2, 0,
  25398. /*read_timeout_sec=*/2, 0,
  25399. /*write_timeout_sec=*/2, 0, std::string(), error);
  25400. ASSERT_NE(INVALID_SOCKET, sock);
  25401. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25402. auto send_request_and_read_response = [&](const std::string &req,
  25403. std::string &out) -> bool {
  25404. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25405. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25406. char buf[4096];
  25407. for (;;) {
  25408. auto n = recv(sock, buf, sizeof(buf), 0);
  25409. if (n <= 0) { return !out.empty(); }
  25410. out.append(buf, static_cast<size_t>(n));
  25411. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25412. }
  25413. };
  25414. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25415. "Host: localhost\r\n"
  25416. "\r\n";
  25417. std::string resp1;
  25418. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25419. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25420. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25421. "Host: localhost\r\n"
  25422. "Connection: close\r\n"
  25423. "\r\n";
  25424. std::string resp2;
  25425. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25426. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25427. EXPECT_EQ(2, delete_count.load());
  25428. }
  25429. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25430. Server svr;
  25431. svr.Post("/ingest", [&](const Request &, Response &res,
  25432. const ContentReader &content_reader) {
  25433. auto consumed = content_reader([](const char *, size_t) { return false; });
  25434. EXPECT_FALSE(consumed);
  25435. res.status = StatusCode::Conflict_409;
  25436. res.set_header("Connection", "close");
  25437. });
  25438. auto port = svr.bind_to_any_port(HOST);
  25439. thread t = thread([&] { svr.listen_after_bind(); });
  25440. auto se = detail::scope_exit([&] {
  25441. svr.stop();
  25442. t.join();
  25443. });
  25444. svr.wait_until_ready();
  25445. auto error = Error::Success;
  25446. auto sock = detail::create_client_socket(
  25447. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25448. /*connection_timeout_sec=*/2, 0,
  25449. /*read_timeout_sec=*/1, 0,
  25450. /*write_timeout_sec=*/2, 0, std::string(), error);
  25451. ASSERT_NE(INVALID_SOCKET, sock);
  25452. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25453. std::string request = "POST /ingest HTTP/1.1\r\n"
  25454. "Host: localhost\r\n"
  25455. "Transfer-Encoding: chunked\r\n"
  25456. "\r\n"
  25457. "4\r\n"
  25458. "data\r\n";
  25459. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25460. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25461. std::string response;
  25462. ssize_t received = 0;
  25463. do {
  25464. char buf[4096];
  25465. received = recv(sock, buf, sizeof(buf), 0);
  25466. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25467. } while (received > 0);
  25468. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25469. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25470. EXPECT_EQ(0, received);
  25471. }
  25472. namespace no_proxy_test {
  25473. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25474. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25475. // calling listen().
  25476. class ScopedServer {
  25477. public:
  25478. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25479. ~ScopedServer() {
  25480. svr_.stop();
  25481. if (th_.joinable()) { th_.join(); }
  25482. }
  25483. Server &svr() { return svr_; }
  25484. int port() const { return port_; }
  25485. void listen() {
  25486. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25487. svr_.wait_until_ready();
  25488. }
  25489. private:
  25490. Server svr_;
  25491. std::thread th_;
  25492. int port_ = 0;
  25493. };
  25494. class ProxyAndTargetServers {
  25495. public:
  25496. ProxyAndTargetServers() {
  25497. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25498. proxy_hits_++;
  25499. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25500. res.set_content("via-proxy", "text/plain");
  25501. });
  25502. target_.Get(".*", [this](const Request &req, Response &res) {
  25503. target_hits_++;
  25504. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25505. res.set_content("direct", "text/plain");
  25506. });
  25507. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25508. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25509. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25510. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25511. proxy_mock_.wait_until_ready();
  25512. target_.wait_until_ready();
  25513. }
  25514. ~ProxyAndTargetServers() {
  25515. proxy_mock_.stop();
  25516. target_.stop();
  25517. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25518. if (target_thread_.joinable()) { target_thread_.join(); }
  25519. }
  25520. Server &proxy_mock() { return proxy_mock_; }
  25521. Server &target() { return target_; }
  25522. int proxy_port() const { return proxy_port_; }
  25523. int target_port() const { return target_port_; }
  25524. int proxy_hits() const { return proxy_hits_.load(); }
  25525. int target_hits() const { return target_hits_.load(); }
  25526. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25527. void reset_counters() {
  25528. proxy_hits_ = 0;
  25529. target_hits_ = 0;
  25530. last_had_proxy_authz_ = false;
  25531. }
  25532. private:
  25533. Server proxy_mock_;
  25534. Server target_;
  25535. std::thread proxy_thread_;
  25536. std::thread target_thread_;
  25537. int proxy_port_ = 0;
  25538. int target_port_ = 0;
  25539. std::atomic<int> proxy_hits_{0};
  25540. std::atomic<int> target_hits_{0};
  25541. std::atomic<bool> last_had_proxy_authz_{false};
  25542. };
  25543. inline std::unique_ptr<Client> make_client(const std::string &host,
  25544. ProxyAndTargetServers &s) {
  25545. auto cli = detail::make_unique<Client>(host, s.target_port());
  25546. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25547. cli->set_proxy("127.0.0.1", s.proxy_port());
  25548. return cli;
  25549. }
  25550. } // namespace no_proxy_test
  25551. using no_proxy_test::make_client;
  25552. using no_proxy_test::ProxyAndTargetServers;
  25553. // A stream request carries the credentials a buffered request does
  25554. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25555. no_proxy_test::ScopedServer origin;
  25556. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25557. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25558. });
  25559. origin.listen();
  25560. Client cli("127.0.0.1", origin.port());
  25561. cli.set_basic_auth("user", "pass");
  25562. auto handle = cli.open_stream("GET", "/x");
  25563. ASSERT_TRUE(handle.is_valid());
  25564. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25565. Client bearer("127.0.0.1", origin.port());
  25566. bearer.set_bearer_token_auth("tok");
  25567. auto handle2 = bearer.open_stream("GET", "/x");
  25568. ASSERT_TRUE(handle2.is_valid());
  25569. EXPECT_EQ("Bearer tok", read_all(handle2));
  25570. }
  25571. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25572. // takes its own credentials, as for a buffered request
  25573. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25574. std::string target, authz, proxy_authz;
  25575. no_proxy_test::ScopedServer proxy;
  25576. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25577. target = req.target;
  25578. authz = req.get_header_value("Authorization");
  25579. proxy_authz = req.get_header_value("Proxy-Authorization");
  25580. res.set_content("ok", "text/plain");
  25581. });
  25582. proxy.listen();
  25583. Client cli("origin.example", 8080);
  25584. cli.set_proxy("127.0.0.1", proxy.port());
  25585. cli.set_proxy_basic_auth("puser", "ppass");
  25586. cli.set_basic_auth("user", "pass");
  25587. auto handle = cli.open_stream("GET", "/x");
  25588. ASSERT_TRUE(handle.is_valid());
  25589. EXPECT_EQ("ok", read_all(handle));
  25590. EXPECT_EQ("http://origin.example:8080/x", target);
  25591. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25592. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25593. }
  25594. TEST(NoProxyTest, ExactHostnameBypasses) {
  25595. ProxyAndTargetServers s;
  25596. auto cli = make_client("example.com", s);
  25597. cli->set_no_proxy({"example.com"});
  25598. auto res = cli->Get("/");
  25599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25600. EXPECT_EQ(0, s.proxy_hits());
  25601. EXPECT_EQ(1, s.target_hits());
  25602. }
  25603. TEST(NoProxyTest, SubdomainBypasses) {
  25604. ProxyAndTargetServers s;
  25605. auto cli = make_client("foo.example.com", s);
  25606. cli->set_no_proxy({"example.com"});
  25607. auto res = cli->Get("/");
  25608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25609. EXPECT_EQ(0, s.proxy_hits());
  25610. EXPECT_EQ(1, s.target_hits());
  25611. }
  25612. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25613. // Regression guard: "evilexample.com" must not be considered a subdomain
  25614. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25615. // check would let traffic bypass the proxy and leak credentials direct
  25616. // to the attacker host.
  25617. ProxyAndTargetServers s;
  25618. auto cli = make_client("evilexample.com", s);
  25619. cli->set_no_proxy({"example.com"});
  25620. auto res = cli->Get("/");
  25621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25622. EXPECT_GE(s.proxy_hits(), 1);
  25623. EXPECT_EQ(0, s.target_hits());
  25624. }
  25625. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25626. ProxyAndTargetServers s;
  25627. auto cli = make_client("example.com.evil.com", s);
  25628. cli->set_no_proxy({"example.com"});
  25629. auto res = cli->Get("/");
  25630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25631. EXPECT_GE(s.proxy_hits(), 1);
  25632. EXPECT_EQ(0, s.target_hits());
  25633. }
  25634. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25635. ProxyAndTargetServers s;
  25636. auto cli = make_client("example.com", s);
  25637. cli->set_no_proxy({".example.com"});
  25638. auto res = cli->Get("/");
  25639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25640. EXPECT_EQ(0, s.proxy_hits());
  25641. EXPECT_EQ(1, s.target_hits());
  25642. }
  25643. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25644. ProxyAndTargetServers s;
  25645. auto cli = make_client("Example.COM", s);
  25646. cli->set_no_proxy({"EXAMPLE.com"});
  25647. auto res = cli->Get("/");
  25648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25649. EXPECT_EQ(0, s.proxy_hits());
  25650. EXPECT_EQ(1, s.target_hits());
  25651. }
  25652. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25653. ProxyAndTargetServers s;
  25654. auto cli = make_client("example.com.", s);
  25655. cli->set_no_proxy({"example.com"});
  25656. auto res = cli->Get("/");
  25657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25658. EXPECT_EQ(0, s.proxy_hits());
  25659. EXPECT_EQ(1, s.target_hits());
  25660. }
  25661. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25662. // Trailing dots must be normalized on BOTH sides — host and entry.
  25663. // An implementation that only strips the host-side trailing dot would
  25664. // fail to match host "example.com" against entry "example.com." because
  25665. // a literal substring search would compare 11 chars against 12.
  25666. ProxyAndTargetServers s;
  25667. auto cli = make_client("example.com", s);
  25668. cli->set_no_proxy({"example.com."});
  25669. auto res = cli->Get("/");
  25670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25671. EXPECT_EQ(0, s.proxy_hits());
  25672. EXPECT_EQ(1, s.target_hits());
  25673. }
  25674. TEST(NoProxyTest, WildcardBypassesEverything) {
  25675. ProxyAndTargetServers s;
  25676. auto cli = make_client("anything.invalid.test", s);
  25677. cli->set_no_proxy({"*"});
  25678. auto res = cli->Get("/");
  25679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25680. EXPECT_EQ(0, s.proxy_hits());
  25681. EXPECT_EQ(1, s.target_hits());
  25682. }
  25683. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25684. ProxyAndTargetServers s;
  25685. Client cli("127.0.0.1", s.target_port());
  25686. cli.set_proxy("127.0.0.1", s.proxy_port());
  25687. cli.set_no_proxy({"127.0.0.1"});
  25688. auto res = cli.Get("/");
  25689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25690. EXPECT_EQ(0, s.proxy_hits());
  25691. EXPECT_EQ(1, s.target_hits());
  25692. }
  25693. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25694. ProxyAndTargetServers s;
  25695. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25696. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25697. cli.set_proxy("127.0.0.1", s.proxy_port());
  25698. cli.set_no_proxy({"::1"});
  25699. auto res = cli.Get("/");
  25700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25701. EXPECT_EQ(0, s.proxy_hits());
  25702. EXPECT_EQ(1, s.target_hits());
  25703. }
  25704. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25705. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25706. // must still be recognized as IPv6 for CIDR matching. Implementations
  25707. // that detect IPv6 only when the host begins with '[' would parse the
  25708. // host as a hostname and miss the match.
  25709. ProxyAndTargetServers s;
  25710. Client cli("fe80::1", s.target_port());
  25711. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25712. cli.set_proxy("127.0.0.1", s.proxy_port());
  25713. cli.set_no_proxy({"fe80::/10"});
  25714. auto res = cli.Get("/");
  25715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25716. EXPECT_EQ(0, s.proxy_hits());
  25717. EXPECT_EQ(1, s.target_hits());
  25718. }
  25719. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25720. ProxyAndTargetServers s;
  25721. Client cli("::1", s.target_port());
  25722. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25723. cli.set_proxy("127.0.0.1", s.proxy_port());
  25724. cli.set_no_proxy({"[::1]"});
  25725. auto res = cli.Get("/");
  25726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25727. EXPECT_EQ(0, s.proxy_hits());
  25728. EXPECT_EQ(1, s.target_hits());
  25729. }
  25730. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25731. ProxyAndTargetServers s;
  25732. Client cli("fe80::1", s.target_port());
  25733. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25734. cli.set_proxy("127.0.0.1", s.proxy_port());
  25735. cli.set_no_proxy({"[fe80::]/10"});
  25736. auto res = cli.Get("/");
  25737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25738. EXPECT_EQ(0, s.proxy_hits());
  25739. EXPECT_EQ(1, s.target_hits());
  25740. }
  25741. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25742. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25743. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25744. // tricks via address-family conversion.
  25745. ProxyAndTargetServers s;
  25746. Client cli("::ffff:127.0.0.1", s.target_port());
  25747. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25748. cli.set_proxy("127.0.0.1", s.proxy_port());
  25749. cli.set_no_proxy({"127.0.0.1"});
  25750. auto res = cli.Get("/");
  25751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25752. EXPECT_GE(s.proxy_hits(), 1);
  25753. EXPECT_EQ(0, s.target_hits());
  25754. }
  25755. TEST(NoProxyTest, IPv4CidrMatch) {
  25756. ProxyAndTargetServers s;
  25757. Client cli("127.0.0.1", s.target_port());
  25758. cli.set_proxy("127.0.0.1", s.proxy_port());
  25759. cli.set_no_proxy({"127.0.0.0/8"});
  25760. auto res = cli.Get("/");
  25761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25762. EXPECT_EQ(0, s.proxy_hits());
  25763. EXPECT_EQ(1, s.target_hits());
  25764. }
  25765. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25766. ProxyAndTargetServers s;
  25767. Client cli("127.0.0.1", s.target_port());
  25768. cli.set_proxy("127.0.0.1", s.proxy_port());
  25769. cli.set_no_proxy({"10.0.0.0/8"});
  25770. auto res = cli.Get("/");
  25771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25772. EXPECT_GE(s.proxy_hits(), 1);
  25773. EXPECT_EQ(0, s.target_hits());
  25774. }
  25775. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25776. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25777. // IPv4 target matches.
  25778. ProxyAndTargetServers s;
  25779. Client cli("127.0.0.1", s.target_port());
  25780. cli.set_proxy("127.0.0.1", s.proxy_port());
  25781. cli.set_no_proxy({"0.0.0.0/0"});
  25782. auto res = cli.Get("/");
  25783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25784. EXPECT_EQ(0, s.proxy_hits());
  25785. EXPECT_EQ(1, s.target_hits());
  25786. }
  25787. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25788. ProxyAndTargetServers s;
  25789. Client cli("127.0.0.1", s.target_port());
  25790. cli.set_proxy("127.0.0.1", s.proxy_port());
  25791. cli.set_no_proxy({"127.0.0.1"});
  25792. auto res = cli.Get("/");
  25793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25794. EXPECT_EQ(0, s.proxy_hits());
  25795. EXPECT_EQ(1, s.target_hits());
  25796. }
  25797. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25798. ProxyAndTargetServers s;
  25799. Client cli("127.0.0.1", s.target_port());
  25800. cli.set_proxy("127.0.0.1", s.proxy_port());
  25801. cli.set_no_proxy({"127.0.0.0/33"});
  25802. auto res = cli.Get("/");
  25803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25804. EXPECT_GE(s.proxy_hits(), 1);
  25805. EXPECT_EQ(0, s.target_hits());
  25806. }
  25807. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25808. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25809. ProxyAndTargetServers s;
  25810. Client cli("127.0.0.1", s.target_port());
  25811. cli.set_proxy("127.0.0.1", s.proxy_port());
  25812. cli.set_no_proxy({"127.0.0.1/"});
  25813. auto res = cli.Get("/");
  25814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25815. EXPECT_GE(s.proxy_hits(), 1);
  25816. EXPECT_EQ(0, s.target_hits());
  25817. }
  25818. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25819. ProxyAndTargetServers s;
  25820. auto cli = make_client("internal.corp", s);
  25821. cli->set_proxy_basic_auth("u", "p");
  25822. cli->set_no_proxy({"internal.corp"});
  25823. auto res = cli->Get("/");
  25824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25825. EXPECT_EQ(1, s.target_hits());
  25826. EXPECT_EQ(0, s.proxy_hits());
  25827. EXPECT_FALSE(s.last_had_proxy_authz())
  25828. << "Proxy-Authorization must not be sent direct to the target";
  25829. }
  25830. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25831. ProxyAndTargetServers s;
  25832. auto cli = make_client("public.example", s);
  25833. cli->set_proxy_basic_auth("u", "p");
  25834. cli->set_no_proxy({"internal.corp"}); // does not match
  25835. auto res = cli->Get("/");
  25836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25837. EXPECT_GE(s.proxy_hits(), 1);
  25838. EXPECT_TRUE(s.last_had_proxy_authz());
  25839. }
  25840. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25841. std::atomic<int> hits{0};
  25842. std::atomic<int> hits_with_authz{0};
  25843. no_proxy_test::ScopedServer proxy_mock;
  25844. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25845. hits++;
  25846. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25847. if (req.target.find("/redir") != std::string::npos) {
  25848. res.set_redirect("http://other.example/landed");
  25849. } else {
  25850. res.set_content("via-proxy", "text/plain");
  25851. }
  25852. });
  25853. proxy_mock.listen();
  25854. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25855. hits = 0;
  25856. hits_with_authz = 0;
  25857. Client cli("public.example", 80);
  25858. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25859. cli.set_proxy_basic_auth(c.first, c.second);
  25860. cli.set_follow_location(true);
  25861. // The redirect to another host goes through the proxy as well
  25862. auto res = cli.Get("/redir");
  25863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25864. EXPECT_EQ(2, hits.load());
  25865. EXPECT_EQ(2, hits_with_authz.load());
  25866. }
  25867. }
  25868. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25869. ProxyAndTargetServers s;
  25870. auto cli = make_client("anything.test", s);
  25871. auto res = cli->Get("/");
  25872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25873. EXPECT_GE(s.proxy_hits(), 1);
  25874. EXPECT_EQ(0, s.target_hits());
  25875. }
  25876. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25877. ProxyAndTargetServers s;
  25878. auto cli = make_client("example.com", s);
  25879. cli->set_no_proxy({"example.com:8080"});
  25880. auto res = cli->Get("/");
  25881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25882. EXPECT_GE(s.proxy_hits(), 1);
  25883. EXPECT_EQ(0, s.target_hits());
  25884. }
  25885. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25886. ProxyAndTargetServers s;
  25887. auto cli = make_client("anything.test", s);
  25888. cli->set_no_proxy({"", " ", "\t"});
  25889. auto res = cli->Get("/");
  25890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25891. EXPECT_GE(s.proxy_hits(), 1);
  25892. EXPECT_EQ(0, s.target_hits());
  25893. }
  25894. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25895. // An entry with leading/trailing whitespace must still match — env-style
  25896. // values are commonly pasted with stray spaces and an implementation
  25897. // that feeds the raw token directly to inet_pton would fail to match
  25898. // valid CIDRs because of the spaces.
  25899. ProxyAndTargetServers s;
  25900. Client cli("127.0.0.1", s.target_port());
  25901. cli.set_proxy("127.0.0.1", s.proxy_port());
  25902. cli.set_no_proxy({" 127.0.0.0/8 "});
  25903. auto res = cli.Get("/");
  25904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25905. EXPECT_EQ(0, s.proxy_hits());
  25906. EXPECT_EQ(1, s.target_hits());
  25907. }
  25908. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25909. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25910. // go direct and must NOT carry Proxy-Authorization.
  25911. std::atomic<int> proxy_hits{0};
  25912. std::atomic<int> target_hits{0};
  25913. std::atomic<bool> target_saw_authz{false};
  25914. no_proxy_test::ScopedServer proxy_mock, target;
  25915. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25916. proxy_hits++;
  25917. res.status = 302;
  25918. res.set_header("Location", "http://127.0.0.1:" +
  25919. std::to_string(target.port()) + "/landed");
  25920. });
  25921. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25922. target_hits++;
  25923. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25924. res.set_content("direct", "text/plain");
  25925. });
  25926. proxy_mock.listen();
  25927. target.listen();
  25928. Client cli("public.example", target.port());
  25929. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25930. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25931. cli.set_proxy_basic_auth("u", "p");
  25932. cli.set_no_proxy({"127.0.0.1"});
  25933. cli.set_follow_location(true);
  25934. auto res = cli.Get("/redir");
  25935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25936. EXPECT_GE(proxy_hits.load(), 1);
  25937. EXPECT_GE(target_hits.load(), 1);
  25938. EXPECT_FALSE(target_saw_authz.load());
  25939. }
  25940. #ifdef CPPHTTPLIB_SSL_ENABLED
  25941. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25942. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25943. // proxy creds would be sent to the (possibly hostile) origin.
  25944. std::atomic<int> target_hits{0};
  25945. std::atomic<bool> target_saw_proxy_authz{false};
  25946. no_proxy_test::ScopedServer target;
  25947. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25948. target_hits++;
  25949. if (req.has_header("Proxy-Authorization")) {
  25950. target_saw_proxy_authz = true;
  25951. }
  25952. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25953. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25954. "nonce=\"abc\", algorithm=MD5");
  25955. });
  25956. target.listen();
  25957. // The proxy address is set to the target's port: the bypass MUST kick in;
  25958. // if it doesn't, the test still routes "via proxy" to the same server and
  25959. // the Proxy-Authorization assertion below catches the leak.
  25960. Client cli("evil.example", target.port());
  25961. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25962. cli.set_proxy("127.0.0.1", target.port());
  25963. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25964. cli.set_no_proxy({"evil.example"});
  25965. auto res = cli.Get("/x");
  25966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25967. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25968. EXPECT_EQ(1, target_hits.load());
  25969. EXPECT_FALSE(target_saw_proxy_authz.load());
  25970. }
  25971. #endif
  25972. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25973. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25974. std::atomic<int> proxy_hits{0};
  25975. std::atomic<int> bypass_hits{0};
  25976. std::atomic<bool> proxy_saw_c_url{false};
  25977. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25978. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25979. proxy_hits++;
  25980. if (req.path.find("/start") != std::string::npos) {
  25981. res.status = 302;
  25982. res.set_header("Location", "http://127.0.0.1:" +
  25983. std::to_string(bypass_server.port()) +
  25984. "/middle");
  25985. return;
  25986. }
  25987. if (req.path.find("/end") != std::string::npos) {
  25988. proxy_saw_c_url = true;
  25989. res.set_content("c-via-proxy", "text/plain");
  25990. return;
  25991. }
  25992. res.set_content("unexpected", "text/plain");
  25993. });
  25994. // public.example's "advertised" port is arbitrary (the request never lands
  25995. // there — it goes through the proxy), but use a dynamic value to stay
  25996. // friendly with sharded parallel runs.
  25997. int public_port = bypass_server.port();
  25998. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25999. bypass_hits++;
  26000. res.status = 302;
  26001. res.set_header("Location", "http://public.example:" +
  26002. std::to_string(public_port) + "/end");
  26003. });
  26004. proxy_mock.listen();
  26005. bypass_server.listen();
  26006. Client cli("public.example", public_port);
  26007. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26008. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26009. cli.set_no_proxy({"127.0.0.1"});
  26010. cli.set_follow_location(true);
  26011. auto res = cli.Get("/start");
  26012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26013. EXPECT_EQ(StatusCode::OK_200, res->status);
  26014. EXPECT_EQ("c-via-proxy", res->body);
  26015. EXPECT_GE(proxy_hits.load(), 2);
  26016. EXPECT_GE(bypass_hits.load(), 1);
  26017. EXPECT_TRUE(proxy_saw_c_url.load());
  26018. }
  26019. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26020. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26021. // request reconnects to the correct endpoint.
  26022. std::atomic<int> proxy_hits{0};
  26023. std::atomic<int> target_hits{0};
  26024. no_proxy_test::ScopedServer proxy_mock, target;
  26025. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26026. proxy_hits++;
  26027. res.set_content("via-proxy", "text/plain");
  26028. });
  26029. target.svr().Get(".*", [&](const Request &, Response &res) {
  26030. target_hits++;
  26031. res.set_content("direct", "text/plain");
  26032. });
  26033. proxy_mock.listen();
  26034. target.listen();
  26035. Client cli("public.example", target.port());
  26036. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26037. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26038. cli.set_keep_alive(true);
  26039. auto res1 = cli.Get("/a");
  26040. ASSERT_TRUE(res1);
  26041. EXPECT_EQ("via-proxy", res1->body);
  26042. EXPECT_EQ(1, proxy_hits.load());
  26043. EXPECT_EQ(0, target_hits.load());
  26044. cli.set_no_proxy({"public.example"});
  26045. auto res2 = cli.Get("/b");
  26046. ASSERT_TRUE(res2);
  26047. EXPECT_EQ("direct", res2->body);
  26048. EXPECT_EQ(1, proxy_hits.load());
  26049. EXPECT_EQ(1, target_hits.load());
  26050. }
  26051. // Forward declarations (see the base64_encode note).
  26052. namespace httplib {
  26053. namespace detail {
  26054. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26055. int shutdown_socket(socket_t sock) noexcept;
  26056. } // namespace detail
  26057. } // namespace httplib
  26058. namespace proxy_tunnel_test {
  26059. const char *const kTunnelEstablished =
  26060. "HTTP/1.1 200 Connection established\r\n\r\n";
  26061. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26062. using ConnectReply = std::function<std::string(const std::string &head)>;
  26063. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26064. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26065. class ScopedConnectProxy {
  26066. public:
  26067. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26068. : forward_port_(forward_port), reply_(std::move(reply)) {
  26069. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26070. if (listen_sock_ == INVALID_SOCKET) { return; }
  26071. auto a = loopback(0);
  26072. auto addr = reinterpret_cast<sockaddr *>(&a);
  26073. socklen_t alen = sizeof(a);
  26074. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26075. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26076. ::listen(listen_sock_, 4) != 0) {
  26077. return;
  26078. }
  26079. port_ = ntohs(a.sin_port);
  26080. th_ = std::thread([this] { run(); });
  26081. }
  26082. ~ScopedConnectProxy() {
  26083. if (th_.joinable()) {
  26084. stop_ = true;
  26085. auto wake = connect_to(port_);
  26086. th_.join();
  26087. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26088. }
  26089. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26090. }
  26091. int port() const { return port_; }
  26092. int connect_hits() const { return connect_hits_.load(); }
  26093. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26094. std::string connect_request() const {
  26095. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26096. return connect_request_;
  26097. }
  26098. private:
  26099. static sockaddr_in loopback(int port) {
  26100. sockaddr_in a{};
  26101. a.sin_family = AF_INET;
  26102. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26103. a.sin_port = htons(static_cast<unsigned short>(port));
  26104. return a;
  26105. }
  26106. static socket_t connect_to(int port) {
  26107. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26108. if (sock == INVALID_SOCKET) { return sock; }
  26109. auto a = loopback(port);
  26110. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26111. detail::close_socket(sock);
  26112. return INVALID_SOCKET;
  26113. }
  26114. return sock;
  26115. }
  26116. static bool send_all(socket_t sock, const char *data, size_t size) {
  26117. while (size > 0) {
  26118. auto n = detail::send_socket(sock, data, size, 0);
  26119. if (n <= 0) { return false; }
  26120. data += n;
  26121. size -= static_cast<size_t>(n);
  26122. }
  26123. return true;
  26124. }
  26125. void run() {
  26126. for (;;) {
  26127. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26128. if (stop_) {
  26129. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26130. return;
  26131. }
  26132. if (client == INVALID_SOCKET) { continue; }
  26133. serve(client);
  26134. detail::close_socket(client);
  26135. }
  26136. }
  26137. void serve(socket_t client) {
  26138. std::string head;
  26139. char buf[2048];
  26140. while (head.find("\r\n\r\n") == std::string::npos) {
  26141. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26142. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26143. if (n <= 0) { return; }
  26144. head.append(buf, static_cast<size_t>(n));
  26145. }
  26146. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26147. connect_hits_++;
  26148. {
  26149. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26150. connect_request_ = head;
  26151. }
  26152. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26153. if (!send_all(client, res.data(), res.size()) ||
  26154. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26155. return;
  26156. }
  26157. auto origin = connect_to(forward_port_);
  26158. if (origin == INVALID_SOCKET) { return; }
  26159. // When either side stops, shut both down so the other pump returns too.
  26160. auto pump = [&](socket_t from, socket_t to) {
  26161. char b[8192];
  26162. for (;;) {
  26163. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26164. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26165. }
  26166. detail::shutdown_socket(client);
  26167. detail::shutdown_socket(origin);
  26168. };
  26169. std::thread up([&] { pump(client, origin); });
  26170. pump(origin, client);
  26171. up.join();
  26172. detail::close_socket(origin);
  26173. }
  26174. int forward_port_;
  26175. ConnectReply reply_;
  26176. socket_t listen_sock_ = INVALID_SOCKET;
  26177. int port_ = 0;
  26178. std::thread th_;
  26179. std::atomic<bool> stop_{false};
  26180. std::atomic<int> connect_hits_{0};
  26181. mutable std::mutex connect_request_mutex_;
  26182. std::string connect_request_;
  26183. };
  26184. } // namespace proxy_tunnel_test
  26185. #ifdef CPPHTTPLIB_SSL_ENABLED
  26186. namespace proxy_tunnel_test {
  26187. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26188. class ScopedSSLServer {
  26189. public:
  26190. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26191. port_ = svr_.bind_to_any_port("127.0.0.1");
  26192. }
  26193. ~ScopedSSLServer() {
  26194. svr_.stop();
  26195. if (th_.joinable()) { th_.join(); }
  26196. }
  26197. SSLServer &svr() { return svr_; }
  26198. int port() const { return port_; }
  26199. void listen() {
  26200. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26201. svr_.wait_until_ready();
  26202. }
  26203. private:
  26204. SSLServer svr_;
  26205. std::thread th_;
  26206. int port_ = 0;
  26207. };
  26208. // Sends one request through the CONNECT proxy to the TLS origin with a
  26209. // credential configured for each hop, and checks that each credential reaches
  26210. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26211. // origin's (every header in origin_headers) on the tunnelled request.
  26212. void CredentialsStayWithTheirHop(
  26213. const std::function<void(SSLClient &)> &set_credentials,
  26214. const std::string &scheme,
  26215. const std::vector<std::string> &origin_headers = {"Authorization"},
  26216. bool stream = false) {
  26217. std::atomic<int> origin_hits{0};
  26218. std::atomic<bool> origin_saw_proxy_authz{false};
  26219. std::atomic<bool> origin_saw_headers{false};
  26220. ScopedSSLServer origin;
  26221. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26222. origin_hits++;
  26223. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26224. origin_saw_headers =
  26225. std::all_of(origin_headers.begin(), origin_headers.end(),
  26226. [&](const std::string &h) { return req.has_header(h); });
  26227. res.set_content("ok", "text/plain");
  26228. });
  26229. origin.listen();
  26230. ScopedConnectProxy proxy(origin.port());
  26231. ASSERT_NE(0, proxy.port());
  26232. // Pinned to 127.0.0.1 for the same reason as the test below.
  26233. SSLClient cli("127.0.0.1", origin.port());
  26234. cli.enable_server_certificate_verification(false);
  26235. cli.set_proxy("127.0.0.1", proxy.port());
  26236. set_credentials(cli);
  26237. if (stream) {
  26238. auto handle = cli.open_stream("GET", "/x");
  26239. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26240. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26241. } else {
  26242. auto res = cli.Get("/x");
  26243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26244. EXPECT_EQ(StatusCode::OK_200, res->status);
  26245. }
  26246. EXPECT_EQ(1, origin_hits.load());
  26247. EXPECT_EQ(1, proxy.connect_hits());
  26248. EXPECT_TRUE(origin_saw_headers.load());
  26249. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26250. << "Proxy-Authorization must not be sent inside the tunnel";
  26251. auto connect_req = proxy.connect_request();
  26252. EXPECT_NE(std::string::npos,
  26253. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26254. for (const auto &h : origin_headers) {
  26255. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26256. << h << " must not be sent to the proxy on CONNECT";
  26257. }
  26258. }
  26259. } // namespace proxy_tunnel_test
  26260. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26261. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26262. [](SSLClient &cli) {
  26263. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26264. cli.set_basic_auth("origin-user", "origin-pass");
  26265. },
  26266. "Basic");
  26267. }
  26268. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26269. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26270. [](SSLClient &cli) {
  26271. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26272. cli.set_basic_auth("origin-user", "origin-pass");
  26273. },
  26274. "Basic", {"Authorization"}, true);
  26275. }
  26276. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26277. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26278. [](SSLClient &cli) {
  26279. cli.set_proxy_bearer_token_auth("proxy-token");
  26280. cli.set_bearer_token_auth("origin-token");
  26281. },
  26282. "Bearer");
  26283. }
  26284. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26285. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26286. [](SSLClient &cli) {
  26287. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26288. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26289. {"Cookie", "sid=origin-session"},
  26290. {"X-Api-Key", "origin-key"}});
  26291. },
  26292. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26293. }
  26294. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26295. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26296. // retry; otherwise proxy creds would be sent to the origin.
  26297. std::atomic<int> origin_hits{0};
  26298. std::atomic<bool> origin_saw_proxy_authz{false};
  26299. proxy_tunnel_test::ScopedSSLServer origin;
  26300. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26301. origin_hits++;
  26302. if (req.has_header("Proxy-Authorization")) {
  26303. origin_saw_proxy_authz = true;
  26304. }
  26305. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26306. res.set_header("Proxy-Authenticate",
  26307. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26308. "algorithm=MD5");
  26309. });
  26310. origin.listen();
  26311. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26312. ASSERT_NE(0, proxy.port());
  26313. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26314. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26315. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26316. // and answer with its own status, making this test flaky.
  26317. SSLClient cli("127.0.0.1", origin.port());
  26318. cli.enable_server_certificate_verification(false);
  26319. cli.set_proxy("127.0.0.1", proxy.port());
  26320. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26321. auto res = cli.Get("/x");
  26322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26323. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26324. EXPECT_EQ(1, origin_hits.load());
  26325. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26326. EXPECT_EQ(1, proxy.connect_hits());
  26327. }
  26328. #endif
  26329. namespace proxy_tunnel_test {
  26330. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26331. // anything else gets a 407 with `challenge`.
  26332. ConnectReply require_proxy_auth(const std::string &expected,
  26333. const std::string &challenge) {
  26334. return [=](const std::string &head) -> std::string {
  26335. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26336. std::string::npos) {
  26337. return kTunnelEstablished;
  26338. }
  26339. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26340. "Proxy-Authenticate: " +
  26341. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26342. };
  26343. }
  26344. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26345. // request, then echoes.
  26346. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26347. ws.send(
  26348. "authorization:" + req.get_header_value("Authorization") +
  26349. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26350. std::string msg;
  26351. while (ws.read(msg)) {
  26352. ws.send(msg);
  26353. }
  26354. }
  26355. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26356. class ScopedWebSocketOrigin {
  26357. public:
  26358. ScopedWebSocketOrigin() {
  26359. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26360. server_.listen();
  26361. }
  26362. int port() const { return server_.port(); }
  26363. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26364. std::string url() const {
  26365. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26366. }
  26367. private:
  26368. no_proxy_test::ScopedServer server_;
  26369. };
  26370. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26371. // passed as a constructor header, and checks that each reaches only its hop.
  26372. void WebSocketCredentialsStayWithTheirHop(
  26373. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26374. const std::string &proxy_authz, const std::string &origin_authz) {
  26375. ScopedWebSocketOrigin origin;
  26376. ScopedConnectProxy proxy(
  26377. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26378. ASSERT_NE(0, proxy.port());
  26379. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26380. client.set_proxy("127.0.0.1", proxy.port());
  26381. set_proxy_credentials(client);
  26382. auto res = client.connect();
  26383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26384. std::string msg;
  26385. ASSERT_TRUE(client.read(msg));
  26386. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26387. client.close();
  26388. EXPECT_EQ(1, proxy.connect_hits());
  26389. EXPECT_EQ(std::string::npos,
  26390. proxy.connect_request().find("\r\nAuthorization: "))
  26391. << "origin credentials must not be sent to the proxy";
  26392. }
  26393. } // namespace proxy_tunnel_test
  26394. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26395. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26396. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26397. ASSERT_NE(0, proxy.port());
  26398. ws::WebSocketClient client(origin.url());
  26399. client.set_proxy("127.0.0.1", proxy.port());
  26400. auto res = client.connect();
  26401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26402. std::string msg;
  26403. ASSERT_TRUE(client.read(msg));
  26404. ASSERT_TRUE(client.send("hello"));
  26405. ASSERT_TRUE(client.read(msg));
  26406. EXPECT_EQ("hello", msg);
  26407. client.close();
  26408. EXPECT_EQ(1, proxy.connect_hits());
  26409. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26410. auto connect_req = proxy.connect_request();
  26411. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26412. EXPECT_NE(std::string::npos,
  26413. connect_req.find("\r\nHost: " + target + "\r\n"));
  26414. }
  26415. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26416. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26417. [](ws::WebSocketClient &cli) {
  26418. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26419. },
  26420. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26421. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26422. }
  26423. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26424. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26425. [](ws::WebSocketClient &cli) {
  26426. cli.set_proxy_bearer_token_auth("proxy-token");
  26427. },
  26428. "Bearer proxy-token", "Bearer origin-token");
  26429. }
  26430. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26431. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26432. proxy_tunnel_test::ScopedConnectProxy proxy(
  26433. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26434. "Basic " + detail::base64_encode("proxy-user:"),
  26435. "Basic realm=\"proxy\""));
  26436. ASSERT_NE(0, proxy.port());
  26437. ws::WebSocketClient client(origin.url());
  26438. client.set_proxy("127.0.0.1", proxy.port());
  26439. client.set_proxy_basic_auth("proxy-user", "");
  26440. auto res = client.connect();
  26441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26442. client.close();
  26443. EXPECT_EQ(1, proxy.connect_hits());
  26444. }
  26445. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26446. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26447. proxy_tunnel_test::ScopedConnectProxy proxy(
  26448. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26449. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26450. ASSERT_NE(0, proxy.port());
  26451. ws::WebSocketClient client(origin.url());
  26452. client.set_proxy("127.0.0.1", proxy.port());
  26453. auto res = client.connect();
  26454. EXPECT_FALSE(res);
  26455. EXPECT_EQ(Error::ProxyConnection, res.error());
  26456. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26457. EXPECT_EQ("Basic realm=\"proxy\"",
  26458. res.get_header_value("Proxy-Authenticate"));
  26459. EXPECT_FALSE(client.is_open());
  26460. }
  26461. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26462. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26463. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26464. ASSERT_NE(0, proxy.port());
  26465. ws::WebSocketClient client(origin.url());
  26466. client.set_proxy("127.0.0.1", proxy.port());
  26467. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26468. client.set_no_proxy({"127.0.0.1"});
  26469. auto res = client.connect();
  26470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26471. std::string msg;
  26472. ASSERT_TRUE(client.read(msg));
  26473. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26474. << "proxy credentials must not reach a bypassed origin";
  26475. client.close();
  26476. EXPECT_EQ(0, proxy.connect_hits());
  26477. }
  26478. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26479. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26480. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26481. ASSERT_NE(0, proxy.port());
  26482. ws::WebSocketClient client(origin.url());
  26483. client.set_proxy("127.0.0.1", proxy.port());
  26484. ASSERT_TRUE(client.connect());
  26485. ASSERT_TRUE(client.connect());
  26486. client.close();
  26487. EXPECT_EQ(2, proxy.connect_hits());
  26488. }
  26489. #ifdef CPPHTTPLIB_SSL_ENABLED
  26490. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26491. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26492. proxy_tunnel_test::ScopedConnectProxy proxy(
  26493. origin.port(), [](const std::string &head) -> std::string {
  26494. if (head.find(
  26495. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26496. std::string::npos) {
  26497. return proxy_tunnel_test::kTunnelEstablished;
  26498. }
  26499. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26500. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26501. "nonce=\"abc\", algorithm=MD5\r\n"
  26502. "Content-Length: 0\r\n\r\n";
  26503. });
  26504. ASSERT_NE(0, proxy.port());
  26505. ws::WebSocketClient client(origin.url());
  26506. client.set_proxy("127.0.0.1", proxy.port());
  26507. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26508. auto res = client.connect();
  26509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26510. std::string msg;
  26511. ASSERT_TRUE(client.read(msg));
  26512. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26513. client.close();
  26514. EXPECT_EQ(2, proxy.connect_hits());
  26515. }
  26516. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26517. proxy_tunnel_test::ScopedSSLServer origin;
  26518. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26519. origin.listen();
  26520. proxy_tunnel_test::ScopedConnectProxy proxy(
  26521. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26522. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26523. ASSERT_NE(0, proxy.port());
  26524. ws::WebSocketClient client(
  26525. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26526. client.enable_server_certificate_verification(false);
  26527. client.set_proxy("127.0.0.1", proxy.port());
  26528. client.set_proxy_bearer_token_auth("proxy-token");
  26529. auto res = client.connect();
  26530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26531. std::string msg;
  26532. ASSERT_TRUE(client.read(msg));
  26533. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26534. << "Proxy-Authorization must not be sent inside the tunnel";
  26535. client.close();
  26536. EXPECT_EQ(1, proxy.connect_hits());
  26537. }
  26538. #endif