test.cc 1024 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507
  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(RangeTest, IgnoredForPost) {
  2318. Server svr;
  2319. svr.Post("/", [](const Request &, Response &res) {
  2320. res.set_content("abcdefg", "text/plain");
  2321. });
  2322. auto port = svr.bind_to_any_port(HOST);
  2323. ASSERT_GT(port, 0);
  2324. thread t = thread([&] { svr.listen_after_bind(); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. t.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. Client cli(HOST, port);
  2332. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2333. auto res = cli.Post("/", Headers{{"Range", range}});
  2334. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2336. EXPECT_EQ("abcdefg", res->body) << range;
  2337. }
  2338. }
  2339. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2340. auto host = "unresolvableaddress.local";
  2341. auto path = std::string{"/"};
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(1);
  2350. {
  2351. auto res = cli.Get(path);
  2352. ASSERT_FALSE(res);
  2353. }
  2354. std::this_thread::sleep_for(std::chrono::seconds(8));
  2355. }
  2356. #if defined(__linux__) && defined(__GLIBC__) && \
  2357. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2358. // Forward declaration: in split builds split.py strips `inline` and moves the
  2359. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2360. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2361. // against the symbol in both header-only and split builds.
  2362. namespace httplib {
  2363. namespace detail {
  2364. int getaddrinfo_with_timeout(const char *node, const char *service,
  2365. const struct addrinfo *hints,
  2366. struct addrinfo **res, time_t timeout_sec);
  2367. } // namespace detail
  2368. } // namespace httplib
  2369. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2370. //
  2371. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2372. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2373. // gai_suspend() call hits the connection timeout the function calls
  2374. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2375. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2376. // still alive and still references the now-destroyed stack frame.
  2377. //
  2378. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2379. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2380. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2381. // and runs them in a container.
  2382. namespace {
  2383. bool should_run_issue_2431_tests() {
  2384. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2385. return v && *v && std::string(v) != "0";
  2386. }
  2387. std::string unique_unresolvable_host(int n) {
  2388. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2389. // glibc still asks the configured nameserver — which is exactly the path
  2390. // we want to exercise. A unique label per call avoids the resolver cache.
  2391. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2392. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2393. std::to_string(n) + ".invalid";
  2394. }
  2395. } // namespace
  2396. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. for (int i = 0; i < 8; ++i) {
  2402. struct addrinfo hints;
  2403. memset(&hints, 0, sizeof(hints));
  2404. hints.ai_family = AF_UNSPEC;
  2405. hints.ai_socktype = SOCK_STREAM;
  2406. auto host = unique_unresolvable_host(i);
  2407. struct addrinfo *result = nullptr;
  2408. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2409. &result, /*timeout_sec=*/1);
  2410. if (rc == 0 && result) { freeaddrinfo(result); }
  2411. }
  2412. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2413. // stack region they still believe holds their gaicb.
  2414. std::this_thread::sleep_for(std::chrono::seconds(3));
  2415. }
  2416. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2417. if (!should_run_issue_2431_tests()) {
  2418. GTEST_SKIP()
  2419. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2420. }
  2421. std::atomic<bool> stop{false};
  2422. std::vector<std::thread> threads;
  2423. for (int t = 0; t < 8; ++t) {
  2424. threads.emplace_back([t, &stop] {
  2425. int i = 0;
  2426. while (!stop.load(std::memory_order_relaxed)) {
  2427. struct addrinfo hints;
  2428. memset(&hints, 0, sizeof(hints));
  2429. hints.ai_family = AF_UNSPEC;
  2430. hints.ai_socktype = SOCK_STREAM;
  2431. auto host = unique_unresolvable_host(t * 100000 + i++);
  2432. struct addrinfo *result = nullptr;
  2433. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2434. &result, /*timeout_sec=*/1);
  2435. if (rc == 0 && result) { freeaddrinfo(result); }
  2436. }
  2437. });
  2438. }
  2439. std::this_thread::sleep_for(std::chrono::seconds(8));
  2440. stop.store(true, std::memory_order_relaxed);
  2441. for (auto &th : threads) {
  2442. th.join();
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(3));
  2445. }
  2446. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2447. if (!should_run_issue_2431_tests()) {
  2448. GTEST_SKIP()
  2449. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2450. }
  2451. std::atomic<bool> stop{false};
  2452. std::vector<std::thread> threads;
  2453. for (int t = 0; t < 8; ++t) {
  2454. threads.emplace_back([t, &stop] {
  2455. int i = 0;
  2456. while (!stop.load(std::memory_order_relaxed)) {
  2457. auto host = unique_unresolvable_host(t * 100000 + i++);
  2458. Client cli(host, 80);
  2459. cli.set_connection_timeout(1, 0);
  2460. cli.set_read_timeout(1, 0);
  2461. cli.set_write_timeout(1, 0);
  2462. (void)cli.Get("/");
  2463. }
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(8));
  2467. stop.store(true, std::memory_order_relaxed);
  2468. for (auto &th : threads) {
  2469. th.join();
  2470. }
  2471. std::this_thread::sleep_for(std::chrono::seconds(3));
  2472. }
  2473. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2474. TEST(ConnectionErrorTest, InvalidHost) {
  2475. auto host = "-abcde.com";
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(std::chrono::seconds(2));
  2484. auto res = cli.Get("/");
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Connection, res.error());
  2487. }
  2488. TEST(ConnectionErrorTest, InvalidHost2) {
  2489. auto host = "httpcan.org/";
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. SSLClient cli(host);
  2492. #else
  2493. Client cli(host);
  2494. #endif
  2495. cli.set_connection_timeout(std::chrono::seconds(2));
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::Connection, res.error());
  2499. }
  2500. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2501. auto host = "httpcan.org/";
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. stringstream s;
  2511. s << "error code: " << res.error();
  2512. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2513. }
  2514. TEST(ConnectionErrorTest, InvalidPort) {
  2515. auto host = "localhost";
  2516. auto port = 44380;
  2517. #ifdef CPPHTTPLIB_SSL_ENABLED
  2518. SSLClient cli(host, port);
  2519. #else
  2520. Client cli(host, port);
  2521. #endif
  2522. cli.set_connection_timeout(std::chrono::seconds(2));
  2523. auto res = cli.Get("/");
  2524. ASSERT_TRUE(!res);
  2525. EXPECT_TRUE(Error::Connection == res.error() ||
  2526. Error::ConnectionTimeout == res.error());
  2527. }
  2528. TEST(ConnectionErrorTest, Timeout_Online) {
  2529. auto host = "google.com";
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 44380;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 8080;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(std::chrono::seconds(2));
  2538. // only probe one address type so that the error reason
  2539. // correlates to the timed-out IPv4, not the unsupported
  2540. // IPv6 connection attempt
  2541. cli.set_address_family(AF_INET);
  2542. auto res = cli.Get("/");
  2543. ASSERT_TRUE(!res);
  2544. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2545. }
  2546. TEST(CancelTest, NoCancel_Online) {
  2547. auto host = "httpbingo.org";
  2548. auto path = std::string{"/range/32"};
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(5));
  2557. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. }
  2562. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2563. // Use /bytes with a large payload so that the DownloadProgress callback
  2564. // (which only fires for Content-Length responses) is invoked before the
  2565. // entire body is received, giving cancellation a chance to fire.
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/bytes/524288"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. auto port = 443;
  2570. SSLClient cli(host, port);
  2571. #else
  2572. auto port = 80;
  2573. Client cli(host, port);
  2574. #endif
  2575. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2576. cli.set_connection_timeout(std::chrono::seconds(5));
  2577. ASSERT_TRUE(!res);
  2578. EXPECT_EQ(Error::Canceled, res.error());
  2579. }
  2580. TEST(CancelTest, WithCancelLargePayload_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/bytes/524288"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. cli.set_connection_timeout(std::chrono::seconds(5));
  2591. uint32_t count = 0;
  2592. auto res =
  2593. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2594. ASSERT_TRUE(!res);
  2595. EXPECT_EQ(Error::Canceled, res.error());
  2596. }
  2597. TEST(CancelTest, NoCancelPost) {
  2598. Server svr;
  2599. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2600. res.set_content("Hello World!", "text/plain");
  2601. });
  2602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli(HOST, PORT);
  2610. cli.set_connection_timeout(std::chrono::seconds(5));
  2611. auto res =
  2612. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2613. "application/json", [](uint64_t, uint64_t) { return true; });
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. EXPECT_EQ("Hello World!", res->body);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2619. Server svr;
  2620. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2621. res.set_content("Hello World!", "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  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, WithCancelLargePayloadPost) {
  2639. Server svr;
  2640. svr.set_payload_max_length(200 * 1024 * 1024);
  2641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content(LARGE_DATA, "text/plain");
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. cli.set_payload_max_length(200 * 1024 * 1024);
  2653. cli.set_connection_timeout(std::chrono::seconds(5));
  2654. auto res =
  2655. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2656. "application/json", [](uint64_t, uint64_t) { return false; });
  2657. ASSERT_TRUE(!res);
  2658. EXPECT_EQ(Error::Canceled, res.error());
  2659. }
  2660. TEST(CancelTest, NoCancelPut) {
  2661. Server svr;
  2662. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. thread.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. Client cli(HOST, PORT);
  2673. cli.set_connection_timeout(std::chrono::seconds(5));
  2674. auto res =
  2675. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2676. "application/json", [](uint64_t, uint64_t) { return true; });
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ("Hello World!", res->body);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. }
  2681. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2682. Server svr;
  2683. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2684. res.set_content("Hello World!", "text/plain");
  2685. });
  2686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. thread.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, PORT);
  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, WithCancelLargePayloadPut) {
  2702. Server svr;
  2703. svr.set_payload_max_length(200 * 1024 * 1024);
  2704. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2705. res.set_content(LARGE_DATA, "text/plain");
  2706. });
  2707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. thread.join();
  2711. ASSERT_FALSE(svr.is_running());
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, PORT);
  2715. cli.set_payload_max_length(200 * 1024 * 1024);
  2716. cli.set_connection_timeout(std::chrono::seconds(5));
  2717. auto res =
  2718. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2719. "application/json", [](uint64_t, uint64_t) { return false; });
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::Canceled, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancelPatch) {
  2724. Server svr;
  2725. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!", "text/plain");
  2727. });
  2728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2729. auto se = detail::scope_exit([&] {
  2730. svr.stop();
  2731. thread.join();
  2732. ASSERT_FALSE(svr.is_running());
  2733. });
  2734. svr.wait_until_ready();
  2735. Client cli(HOST, PORT);
  2736. cli.set_connection_timeout(std::chrono::seconds(5));
  2737. auto res =
  2738. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2739. "application/json", [](uint64_t, uint64_t) { return true; });
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ("Hello World!", res->body);
  2742. EXPECT_EQ(StatusCode::OK_200, res->status);
  2743. }
  2744. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2745. Server svr;
  2746. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2747. res.set_content("Hello World!", "text/plain");
  2748. });
  2749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, PORT);
  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, WithCancelLargePayloadPatch) {
  2765. Server svr;
  2766. svr.set_payload_max_length(200 * 1024 * 1024);
  2767. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2768. res.set_content(LARGE_DATA, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. cli.set_payload_max_length(200 * 1024 * 1024);
  2779. cli.set_connection_timeout(std::chrono::seconds(5));
  2780. auto res =
  2781. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2782. "application/json", [](uint64_t, uint64_t) { return false; });
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Canceled, res.error());
  2785. }
  2786. TEST(CancelTest, NoCancelDelete) {
  2787. Server svr;
  2788. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2789. res.set_content("Hello World!", "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. cli.set_connection_timeout(std::chrono::seconds(5));
  2800. auto res =
  2801. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2802. "application/json", [](uint64_t, uint64_t) { return true; });
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ("Hello World!", res->body);
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. }
  2807. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2808. Server svr;
  2809. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2810. res.set_content("Hello World!", "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  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. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2828. Server svr;
  2829. svr.set_payload_max_length(200 * 1024 * 1024);
  2830. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2831. res.set_content(LARGE_DATA, "text/plain");
  2832. });
  2833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2834. auto se = detail::scope_exit([&] {
  2835. svr.stop();
  2836. thread.join();
  2837. ASSERT_FALSE(svr.is_running());
  2838. });
  2839. svr.wait_until_ready();
  2840. Client cli(HOST, PORT);
  2841. cli.set_payload_max_length(200 * 1024 * 1024);
  2842. cli.set_connection_timeout(std::chrono::seconds(5));
  2843. auto res =
  2844. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2845. "application/json", [](uint64_t, uint64_t) { return false; });
  2846. ASSERT_TRUE(!res);
  2847. EXPECT_EQ(Error::Canceled, res.error());
  2848. }
  2849. static std::string remove_whitespace(const std::string &input) {
  2850. std::string output;
  2851. output.reserve(input.size());
  2852. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2853. [](unsigned char c) { return !std::isspace(c); });
  2854. return output;
  2855. }
  2856. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2857. auto host = "httpbingo.org";
  2858. auto path = std::string{"/basic-auth/hello/world"};
  2859. #ifdef CPPHTTPLIB_SSL_ENABLED
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. #else
  2863. auto port = 80;
  2864. Client cli(host, port);
  2865. #endif
  2866. {
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. auto res = cli.Get(
  2873. path, Headers{make_basic_authentication_header("hello", "world")});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "world");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. auto body = remove_whitespace(res->body);
  2885. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2886. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. {
  2890. cli.set_basic_auth("hello", "bad");
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("bad", "world");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. }
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2904. auto host = "httpbingo.org";
  2905. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2906. auto paths = std::vector<std::string>{
  2907. "/digest-auth/auth/hello/world/MD5",
  2908. "/digest-auth/auth/hello/world/SHA-256",
  2909. };
  2910. auto port = 443;
  2911. SSLClient cli(host, port);
  2912. {
  2913. auto res = cli.Get(unauth_path);
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2916. }
  2917. {
  2918. cli.set_digest_auth("hello", "world");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. auto body = remove_whitespace(res->body);
  2923. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2924. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. cli.set_digest_auth("hello", "bad");
  2928. for (const auto &path : paths) {
  2929. auto res = cli.Get(path.c_str());
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. }
  2934. }
  2935. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2936. // comma-separated list of challenges, and each challenge may itself carry a
  2937. // comma-separated auth-param list, so a server can legally offer Basic
  2938. // before Digest, either as two field lines or packed into one. Runs one 401
  2939. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2940. // value() joins them in receipt order) and checks that the retry carries a
  2941. // well-formed Digest Authorization header naming expected_realm.
  2942. static void
  2943. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2944. const std::string &expected_realm) {
  2945. std::atomic<int> hits{0};
  2946. Server svr;
  2947. svr.Get("/x", [&](const Request &req, Response &res) {
  2948. if (++hits == 1) {
  2949. res.status = StatusCode::Unauthorized_401;
  2950. for (const auto &challenge : challenges) {
  2951. res.set_header("WWW-Authenticate", challenge);
  2952. }
  2953. } else {
  2954. auto authorization = req.get_header_value("Authorization");
  2955. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2956. EXPECT_NE(std::string::npos,
  2957. authorization.find("realm=\"" + expected_realm + "\""));
  2958. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2959. res.set_content("ok", "text/plain");
  2960. }
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. std::thread t([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. t.join();
  2967. });
  2968. svr.wait_until_ready();
  2969. Client cli(HOST, port);
  2970. cli.set_digest_auth("hello", "world");
  2971. auto res = cli.Get("/x");
  2972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2973. EXPECT_EQ(2, hits.load());
  2974. }
  2975. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2976. static const char *kDigestChallenge =
  2977. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2978. "algorithm=MD5";
  2979. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2980. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2981. "testrealm");
  2982. }
  2983. // Same challenge list with the schemes in the opposite order, to make sure
  2984. // the fix above didn't just special-case "Basic first".
  2985. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2986. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2987. "testrealm");
  2988. }
  2989. // A comma inside a quoted auth-param value must not be mistaken for the
  2990. // separator between two challenges (or two auth-params).
  2991. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2992. run_digest_challenge_list_test(
  2993. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2994. "algorithm=MD5"},
  2995. "test,realm");
  2996. }
  2997. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2998. // the params and leaves out the fragment.
  2999. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3000. Server svr;
  3001. std::string uri, target;
  3002. svr.Get("/a b", [&](const Request &req, Response &res) {
  3003. auto auth = req.get_header_value("Authorization");
  3004. if (auth.empty()) {
  3005. res.status = StatusCode::Unauthorized_401;
  3006. res.set_header("WWW-Authenticate",
  3007. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3008. return;
  3009. }
  3010. auto b = auth.find("uri=\"") + 5;
  3011. uri = auth.substr(b, auth.find('"', b) - b);
  3012. target = req.target;
  3013. });
  3014. auto port = svr.bind_to_any_port(HOST);
  3015. std::thread t([&]() { svr.listen_after_bind(); });
  3016. auto se = detail::scope_exit([&] {
  3017. svr.stop();
  3018. t.join();
  3019. });
  3020. svr.wait_until_ready();
  3021. Client cli(HOST, port);
  3022. cli.set_digest_auth("hello", "world");
  3023. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ("/a%20b?x=1", target);
  3026. EXPECT_EQ(target, uri);
  3027. }
  3028. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3029. // make_digest_authentication_header() dereferences both unconditionally, so
  3030. // a server sending a challenge missing either one must not be treated as
  3031. // usable -- doing so used to crash the client with std::out_of_range.
  3032. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3033. Server svr;
  3034. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3035. res.status = StatusCode::Unauthorized_401;
  3036. res.set_header("WWW-Authenticate", challenge);
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/x");
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3050. }
  3051. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3052. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3053. }
  3054. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3055. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3059. }
  3060. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3061. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3062. // when storing the values, so the header builder has to re-escape them (and
  3063. // keep algorithm a bare token); otherwise the value breaks out of its
  3064. // quoted-string and injects extra auth-params into the client's Authorization.
  3065. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3066. std::atomic<int> hits{0};
  3067. std::string authorization;
  3068. Server svr;
  3069. svr.Get("/x", [&](const Request &req, Response &res) {
  3070. if (++hits == 1) {
  3071. res.status = StatusCode::Unauthorized_401;
  3072. // On the wire the quotes embedded in the values are backslash-escaped.
  3073. res.set_header("WWW-Authenticate",
  3074. "Digest realm=\"testrealm\", "
  3075. "nonce=\"n\\\"; injected=\\\"x\", "
  3076. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3077. } else {
  3078. authorization = req.get_header_value("Authorization");
  3079. res.set_content("ok", "text/plain");
  3080. }
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. std::thread t([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. t.join();
  3087. });
  3088. svr.wait_until_ready();
  3089. Client cli(HOST, port);
  3090. cli.set_digest_auth("hello", "world");
  3091. auto res = cli.Get("/x");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(2, hits.load());
  3094. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3095. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3096. // inside its quoted-string rather than starting an "injected" auth-param.
  3097. EXPECT_NE(std::string::npos,
  3098. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3099. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3100. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3101. }
  3102. #endif
  3103. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3104. auto host = "google.com";
  3105. auto another_host = "example.com";
  3106. auto wrong_ip = "0.0.0.0";
  3107. #ifdef CPPHTTPLIB_SSL_ENABLED
  3108. SSLClient cli(host);
  3109. #else
  3110. Client cli(host);
  3111. #endif
  3112. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3113. auto res = cli.Get("/");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3116. }
  3117. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3118. auto host = "google.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(!res);
  3128. EXPECT_EQ(Error::Connection, res.error());
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3131. // A mapped value that is not an IP literal must be resolved. "localhost"
  3132. // resolves from the hosts file, so this test needs no external DNS.
  3133. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3134. auto host = "target.invalid";
  3135. Server svr;
  3136. std::string received_host;
  3137. svr.Get("/hi", [&](const Request &req, Response &res) {
  3138. received_host = req.get_header_value("Host");
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, HOST}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. // The mapping only redirects the connection; the identity stays host_.
  3155. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3156. }
  3157. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3158. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3159. auto host = "target.invalid";
  3160. Server svr;
  3161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3162. res.set_content("Hello World!", "text/plain");
  3163. });
  3164. auto port = svr.bind_to_any_port("127.0.0.1");
  3165. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3166. auto se = detail::scope_exit([&] {
  3167. svr.stop();
  3168. thread.join();
  3169. ASSERT_FALSE(svr.is_running());
  3170. });
  3171. svr.wait_until_ready();
  3172. Client cli(host, port);
  3173. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3174. auto res = cli.Get("/hi");
  3175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3176. EXPECT_EQ(StatusCode::OK_200, res->status);
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3179. // An empty mapped value must leave host_ as the connection target. Without
  3180. // that guard the empty value would become the host argument, getaddrinfo
  3181. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3182. // loopback - silently connecting somewhere the caller never asked for.
  3183. // The server listens on loopback, so such a fallback would succeed and is
  3184. // therefore observable as a failure of this test.
  3185. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3186. Server svr;
  3187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. });
  3190. auto port = svr.bind_to_any_port(HOST);
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(blackhole, port);
  3199. cli.set_hostname_addr_map({{blackhole, ""}});
  3200. cli.set_connection_timeout(1);
  3201. auto res = cli.Get("/hi");
  3202. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3203. }
  3204. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3205. auto host = "httpbingo.org";
  3206. auto path = std::string{"/absolute-redirect/3"};
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. SSLClient cli(host);
  3209. #else
  3210. Client cli(host);
  3211. #endif
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get(path);
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(RedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RelativeRedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/relative-redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(TooManyRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/redirect/21"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(!res);
  3254. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3255. }
  3256. #ifdef CPPHTTPLIB_SSL_ENABLED
  3257. TEST(YahooRedirectTest, Redirect_Online) {
  3258. Client cli("yahoo.com");
  3259. auto res = cli.Get("/");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3262. cli.set_follow_location(true);
  3263. res = cli.Get("/");
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3267. }
  3268. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3269. #define REDIR_HOST "httpbingo.org"
  3270. #define REDIR_PATH "/redirect-to"
  3271. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3272. SSLClient cli(REDIR_HOST);
  3273. cli.set_follow_location(true);
  3274. auto res =
  3275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. params.emplace("status_code", "302");
  3285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3290. SSLClient cli(REDIR_HOST);
  3291. cli.set_follow_location(true);
  3292. Params params;
  3293. params.emplace("url", "http://example.com");
  3294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. TEST(UrlWithSpace, Redirect_Online) {
  3299. SSLClient cli("edge.forgecdn.net");
  3300. cli.set_follow_location(true);
  3301. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3305. }
  3306. #endif
  3307. #if !defined(_WIN32) && !defined(_WIN64)
  3308. TEST(ReceiveSignals, Signal) {
  3309. auto setupSignalHandlers = []() {
  3310. struct sigaction act;
  3311. sigemptyset(&act.sa_mask);
  3312. act.sa_flags = SA_SIGINFO;
  3313. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3314. switch (sig) {
  3315. case SIGINT:
  3316. default: break;
  3317. }
  3318. };
  3319. ::sigaction(SIGINT, &act, nullptr);
  3320. };
  3321. Server svr;
  3322. int port = 0;
  3323. auto thread = std::thread([&]() {
  3324. setupSignalHandlers();
  3325. port = svr.bind_to_any_port(HOST);
  3326. svr.listen_after_bind();
  3327. });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. ASSERT_TRUE(svr.is_running());
  3335. pthread_kill(thread.native_handle(), SIGINT);
  3336. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3337. ASSERT_TRUE(svr.is_running());
  3338. }
  3339. #endif
  3340. TEST(RedirectToDifferentPort, Redirect) {
  3341. Server svr1;
  3342. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3343. res.set_content("Hello World!", "text/plain");
  3344. });
  3345. int svr1_port = 0;
  3346. auto thread1 = std::thread([&]() {
  3347. svr1_port = svr1.bind_to_any_port(HOST);
  3348. svr1.listen_after_bind();
  3349. });
  3350. Server svr2;
  3351. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3352. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3353. });
  3354. int svr2_port = 0;
  3355. auto thread2 = std::thread([&]() {
  3356. svr2_port = svr2.bind_to_any_port(HOST);
  3357. svr2.listen_after_bind();
  3358. });
  3359. auto se = detail::scope_exit([&] {
  3360. svr2.stop();
  3361. thread2.join();
  3362. svr1.stop();
  3363. thread1.join();
  3364. ASSERT_FALSE(svr2.is_running());
  3365. ASSERT_FALSE(svr1.is_running());
  3366. });
  3367. svr1.wait_until_ready();
  3368. svr2.wait_until_ready();
  3369. Client cli("localhost", svr2_port);
  3370. cli.set_follow_location(true);
  3371. auto res = cli.Get("/2");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. EXPECT_EQ("Hello World!", res->body);
  3375. }
  3376. // GET /redir on one server redirects to /target on another port, so the
  3377. // client follows it with a new client.
  3378. static Result
  3379. GetThroughRedirectToDifferentPort(Server::Handler target,
  3380. const std::function<void(Client &)> &setup,
  3381. const Headers &headers = Headers()) {
  3382. Server target_svr;
  3383. target_svr.Get("/target", target);
  3384. int target_port = 0;
  3385. auto target_thread = std::thread([&]() {
  3386. target_port = target_svr.bind_to_any_port(HOST);
  3387. target_svr.listen_after_bind();
  3388. });
  3389. Server origin_svr;
  3390. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3391. res.set_redirect(
  3392. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3393. });
  3394. int origin_port = 0;
  3395. auto origin_thread = std::thread([&]() {
  3396. origin_port = origin_svr.bind_to_any_port(HOST);
  3397. origin_svr.listen_after_bind();
  3398. });
  3399. auto se = detail::scope_exit([&] {
  3400. origin_svr.stop();
  3401. origin_thread.join();
  3402. target_svr.stop();
  3403. target_thread.join();
  3404. });
  3405. target_svr.wait_until_ready();
  3406. origin_svr.wait_until_ready();
  3407. Client cli("localhost", origin_port);
  3408. cli.set_follow_location(true);
  3409. setup(cli);
  3410. return cli.Get("/redir", headers);
  3411. }
  3412. static void
  3413. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3414. std::string captured_authorization;
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [&](const Request &req, Response &res) {
  3417. captured_authorization = req.get_header_value("Authorization");
  3418. res.set_content("OK", "text/plain");
  3419. },
  3420. set_auth);
  3421. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3422. EXPECT_EQ(StatusCode::OK_200, result->status);
  3423. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3424. EXPECT_TRUE(captured_authorization.empty());
  3425. }
  3426. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3427. TestDoNotForwardCredentialsOnRedirect(
  3428. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3429. }
  3430. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3431. TestDoNotForwardCredentialsOnRedirect(
  3432. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3433. }
  3434. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3435. std::string captured_cookie;
  3436. auto result = GetThroughRedirectToDifferentPort(
  3437. [&](const Request &req, Response &res) {
  3438. captured_cookie = req.get_header_value("Cookie");
  3439. res.set_content("OK", "text/plain");
  3440. },
  3441. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3442. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3443. EXPECT_EQ(StatusCode::OK_200, result->status);
  3444. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3445. EXPECT_TRUE(captured_cookie.empty());
  3446. }
  3447. TEST(RedirectToSamePort, ForwardCookie) {
  3448. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3449. // header so that ordinary session flows keep working.
  3450. Server svr;
  3451. std::string captured_cookie;
  3452. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3453. res.set_redirect("/target", 302);
  3454. });
  3455. svr.Get("/target", [&](const Request &req, Response &res) {
  3456. captured_cookie = req.get_header_value("Cookie");
  3457. res.set_content("OK", "text/plain");
  3458. });
  3459. auto port = svr.bind_to_any_port(HOST);
  3460. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. Client cli(HOST, port);
  3468. cli.set_follow_location(true);
  3469. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3470. auto res = cli.Get("/redir", headers);
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3474. }
  3475. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3476. std::string authorization;
  3477. std::string trace_id;
  3478. auto result = GetThroughRedirectToDifferentPort(
  3479. [&](const Request &req, Response &res) {
  3480. authorization = req.get_header_value("Authorization");
  3481. trace_id = req.get_header_value("X-Trace-Id");
  3482. res.set_content("OK", "text/plain");
  3483. },
  3484. [](Client &cli) {
  3485. cli.set_default_headers(
  3486. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3487. });
  3488. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3489. EXPECT_EQ(StatusCode::OK_200, result->status);
  3490. // Like a header given with the request, a default one goes along unless it
  3491. // carries credentials (RFC 9110 15.4).
  3492. EXPECT_TRUE(authorization.empty());
  3493. EXPECT_EQ("42", trace_id);
  3494. }
  3495. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.set_content(std::string(2048, 'x'), "text/plain");
  3499. },
  3500. [](Client &cli) { cli.set_payload_max_length(1024); });
  3501. EXPECT_FALSE(result);
  3502. }
  3503. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3504. auto result = GetThroughRedirectToDifferentPort(
  3505. [](const Request &req, Response &res) {
  3506. // Answer after a second, or once the client gives up.
  3507. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3509. }
  3510. res.set_content("late", "text/plain");
  3511. },
  3512. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3513. ASSERT_FALSE(result);
  3514. EXPECT_EQ(Error::Read, result.error());
  3515. }
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3518. auto result = GetThroughRedirectToDifferentPort(
  3519. [](const Request &, Response &res) {
  3520. res.status = StatusCode::Unauthorized_401;
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3523. },
  3524. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3527. }
  3528. #endif
  3529. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3530. Server svr;
  3531. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3532. // Port number that overflows int — should not crash
  3533. res.set_redirect("http://localhost:99999999999999999999/target");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, port);
  3544. cli.set_follow_location(true);
  3545. auto res = cli.Get("/redir");
  3546. // Should fail gracefully, not crash (no valid response due to bad port)
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3550. Server svr;
  3551. auto port = svr.bind_to_any_port(HOST);
  3552. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3553. // The server's own port followed by junk must not be followed
  3554. res.set_redirect("http://" + std::string(HOST) + ":" +
  3555. std::to_string(port) + "junk/target");
  3556. });
  3557. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3558. res.set_content("target", "text/plain");
  3559. });
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. EXPECT_FALSE(res);
  3571. }
  3572. TEST(RedirectFromPageWithContent, Redirect) {
  3573. Server svr;
  3574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3575. res.set_content("___", "text/plain");
  3576. res.set_redirect("/2");
  3577. });
  3578. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. th.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli("localhost", PORT);
  3590. cli.set_follow_location(true);
  3591. std::string body;
  3592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3593. body.append(data, data_length);
  3594. return true;
  3595. });
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("Hello World!", body);
  3599. }
  3600. {
  3601. Client cli("localhost", PORT);
  3602. std::string body;
  3603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3604. body.append(data, data_length);
  3605. return true;
  3606. });
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::Found_302, res->status);
  3609. EXPECT_EQ("___", body);
  3610. }
  3611. }
  3612. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3613. Server svr;
  3614. auto port_str = std::to_string(PORT);
  3615. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3616. auto expected_host = "[::1]:" + port_str;
  3617. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("___", "text/plain");
  3619. // res.set_redirect("/2");
  3620. res.set_redirect(redirect_url);
  3621. });
  3622. svr.Get("/2", [&](const Request &req, Response &res) {
  3623. auto host_header = req.headers.find("Host");
  3624. ASSERT_TRUE(host_header != req.headers.end());
  3625. EXPECT_EQ(expected_host, host_header->second);
  3626. res.set_content("Hello World!", "text/plain");
  3627. });
  3628. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3629. auto se = detail::scope_exit([&] {
  3630. svr.stop();
  3631. th.join();
  3632. ASSERT_FALSE(svr.is_running());
  3633. });
  3634. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3635. // actually starts anything, so the condition !svr.is_running() will
  3636. // always remain true, and the loop never stops.
  3637. // This basically counts how many milliseconds have passed since the
  3638. // call to svr.listen(), and if after 5 seconds nothing started yet
  3639. // aborts the test.
  3640. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3641. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3642. ASSERT_LT(milliseconds, 5000U);
  3643. }
  3644. {
  3645. Client cli("::1", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("::1", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3669. Server svr;
  3670. svr.Get("/foo", [](const Request &req, Response &res) {
  3671. auto a = req.params.find("a");
  3672. if (a != req.params.end()) {
  3673. res.set_content((*a).second, "text/plain");
  3674. res.status = StatusCode::OK_200;
  3675. } else {
  3676. res.status = StatusCode::BadRequest_400;
  3677. }
  3678. });
  3679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3680. auto se = detail::scope_exit([&] {
  3681. svr.stop();
  3682. thread.join();
  3683. ASSERT_FALSE(svr.is_running());
  3684. });
  3685. svr.wait_until_ready();
  3686. {
  3687. Client cli(HOST, PORT);
  3688. cli.set_path_encode(false);
  3689. auto res = cli.Get("/foo?a=explicitly+encoded");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. // This expects it back with a space, as the `+` won't have been
  3693. // url-encoded, and server-side the params get decoded turning `+`
  3694. // into spaces.
  3695. EXPECT_EQ("explicitly encoded", res->body);
  3696. }
  3697. }
  3698. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3699. // When path encoding is disabled the client must transmit the supplied
  3700. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3701. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3702. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3703. // than a space (0x20). Assert on the raw wire target to catch this.
  3704. Server svr;
  3705. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3706. svr.Get("/foo", [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(expected_target, req.target);
  3708. res.status = StatusCode::OK_200;
  3709. });
  3710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3711. auto se = detail::scope_exit([&] {
  3712. svr.stop();
  3713. thread.join();
  3714. ASSERT_FALSE(svr.is_running());
  3715. });
  3716. svr.wait_until_ready();
  3717. {
  3718. Client cli(HOST, PORT);
  3719. cli.set_path_encode(false);
  3720. auto res = cli.Get(expected_target.c_str());
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. }
  3724. }
  3725. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3726. // `open_stream()` used to skip the path encoding that the buffered send
  3727. // path applies, so the same `path` produced different bytes in the request
  3728. // line depending on which API was used. Assert the two agree.
  3729. Server svr;
  3730. std::string target;
  3731. svr.Get(".*", [&](const Request &req, Response &res) {
  3732. target = req.target;
  3733. res.status = StatusCode::OK_200;
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. struct {
  3744. const char *path;
  3745. const char *expected;
  3746. } cases[] = {
  3747. {"/a b?x=1", "/a%20b?x=1"},
  3748. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3749. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3750. };
  3751. for (const auto &c : cases) {
  3752. Client cli(HOST, port);
  3753. target.clear();
  3754. auto res = cli.Get(c.path);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3757. auto buffered_target = target;
  3758. target.clear();
  3759. auto handle = cli.open_stream("GET", c.path);
  3760. EXPECT_TRUE(handle.is_valid())
  3761. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3762. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3763. }
  3764. }
  3765. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3766. // The `set_path_encode(false)` contract — transmit the supplied target
  3767. // verbatim — must hold for the streaming API too.
  3768. Server svr;
  3769. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, port);
  3785. cli.set_path_encode(false);
  3786. auto handle = cli.open_stream("GET", expected_target);
  3787. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3788. EXPECT_EQ(expected_target, target);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3792. // With path encoding enabled a CR/LF in the target is percent-encoded
  3793. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3794. // write_request_line still backstops `set_path_encode(false)`, which is
  3795. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3796. Server svr;
  3797. // Captured before routing: the decoded path contains a newline, which a
  3798. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3799. std::string target;
  3800. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. return Server::HandlerResponse::Handled;
  3804. });
  3805. auto port = svr.bind_to_any_port(HOST);
  3806. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. {
  3814. Client cli(HOST, port);
  3815. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3816. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3817. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3818. }
  3819. }
  3820. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3821. // Every control character is percent-encoded, not just CR/LF, so the target
  3822. // passes the request-target check in write_request_line.
  3823. Server svr;
  3824. std::string target;
  3825. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3826. target = req.target;
  3827. res.status = StatusCode::OK_200;
  3828. return Server::HandlerResponse::Handled;
  3829. });
  3830. auto port = svr.bind_to_any_port(HOST);
  3831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli(HOST, port);
  3840. auto res = cli.Get("/a\tb\x1b\x7f");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ("/a%09b%1B%7F", target);
  3843. }
  3844. }
  3845. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3846. // Nothing may reach the wire: a raw CR/LF target would split the request
  3847. // line and inject headers.
  3848. Server svr;
  3849. // Pre-routing so that "not called" means nothing reached the server at all,
  3850. // rather than merely failing to match a handler pattern.
  3851. auto handler_called = false;
  3852. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3853. handler_called = true;
  3854. res.status = StatusCode::OK_200;
  3855. return Server::HandlerResponse::Handled;
  3856. });
  3857. auto port = svr.bind_to_any_port(HOST);
  3858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. {
  3866. Client cli(HOST, port);
  3867. cli.set_path_encode(false);
  3868. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3869. EXPECT_FALSE(handle.is_valid());
  3870. EXPECT_EQ(Error::Write, handle.error);
  3871. EXPECT_FALSE(handler_called);
  3872. }
  3873. }
  3874. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3875. // Which of the two branches runs is decided by whether the query component
  3876. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3877. // an empty query and must still fall back to building one from
  3878. // `req.params`, while a non-empty query must win over `req.params`.
  3879. Server svr;
  3880. std::string target;
  3881. svr.Get("/foo", [&](const Request &req, Response &res) {
  3882. target = req.target;
  3883. res.status = StatusCode::OK_200;
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. // Trailing `?` -> empty query component -> `req.params` is used.
  3895. Client cli(HOST, port);
  3896. Request req;
  3897. req.method = "GET";
  3898. req.path = "/foo?";
  3899. req.params.emplace("a", "1");
  3900. target.clear();
  3901. auto res = cli.send(req);
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ("/foo?a=1", target);
  3904. }
  3905. {
  3906. // Non-empty query in `req.path` -> `req.params` is not appended.
  3907. Client cli(HOST, port);
  3908. Request req;
  3909. req.method = "GET";
  3910. req.path = "/foo?b=2";
  3911. req.params.emplace("a", "1");
  3912. target.clear();
  3913. auto res = cli.send(req);
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ("/foo?b=2", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3919. Server svr;
  3920. svr.Get("/", [](const Request &req, Response &) {
  3921. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3922. });
  3923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. {
  3931. Client cli(HOST, PORT);
  3932. cli.set_path_encode(false);
  3933. auto res = cli.Get("/?something=%0A");
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. }
  3938. TEST(BindServerTest, BindDualStack) {
  3939. Server svr;
  3940. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("Hello World!", "text/plain");
  3942. });
  3943. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. {
  3951. Client cli("127.0.0.1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. {
  3958. Client cli("::1", PORT);
  3959. auto res = cli.Get("/1");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("Hello World!", res->body);
  3963. }
  3964. }
  3965. TEST(BindServerTest, BindAndListenSeparately) {
  3966. Server svr;
  3967. int port = svr.bind_to_any_port("0.0.0.0");
  3968. ASSERT_TRUE(svr.is_valid());
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. }
  3972. // Reports whether anything is still listening on a loopback port. A plain
  3973. // connect() is used instead of a Client request because a socket left bound by
  3974. // mistake accepts the connection into its backlog and never answers, which
  3975. // would hang the test instead of failing it.
  3976. static bool is_loopback_port_accepting(int port) {
  3977. sockaddr_in addr{};
  3978. addr.sin_family = AF_INET;
  3979. addr.sin_port = htons(static_cast<uint16_t>(port));
  3980. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3981. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3982. EXPECT_NE(sock, INVALID_SOCKET);
  3983. if (sock == INVALID_SOCKET) { return false; }
  3984. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3985. static_cast<socklen_t>(sizeof(addr)));
  3986. detail::close_socket(sock);
  3987. return ret == 0;
  3988. }
  3989. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3990. Server svr;
  3991. auto port = svr.bind_to_any_port("127.0.0.1");
  3992. ASSERT_TRUE(port > 0);
  3993. svr.stop();
  3994. // bind_to_any_port() already called listen(2), so until stop() closed the
  3995. // descriptor the port kept accepting connections into the backlog. ASSERT
  3996. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3997. // below blocks forever in the accept loop.
  3998. ASSERT_FALSE(is_loopback_port_accepting(port));
  3999. // Nothing is left to accept on, so listen_after_bind() must report failure
  4000. // instead of returning success without ever serving.
  4001. EXPECT_FALSE(svr.listen_after_bind());
  4002. // The failed listen marks the server decommissioned, so a waiter returns
  4003. // instead of spinning forever.
  4004. svr.wait_until_ready();
  4005. }
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. int port = svr.bind_to_any_port("0.0.0.0");
  4011. ASSERT_TRUE(svr.is_valid());
  4012. ASSERT_TRUE(port > 0);
  4013. svr.stop();
  4014. }
  4015. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4016. // or a rejected CustomRoute() registration would not stop the server binding.
  4017. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4019. CLIENT_CA_CERT_DIR);
  4020. ASSERT_TRUE(svr.is_valid());
  4021. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4022. EXPECT_FALSE(svr.is_valid());
  4023. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4024. }
  4025. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4026. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4027. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. svr.stop();
  4032. }
  4033. TEST(BindServerTest, UpdateCertsPem) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4035. int port = svr.bind_to_any_port("0.0.0.0");
  4036. ASSERT_TRUE(svr.is_valid());
  4037. ASSERT_TRUE(port > 0);
  4038. // Read PEM files
  4039. std::string cert_pem, key_pem, ca_pem;
  4040. read_file(SERVER_CERT_FILE, cert_pem);
  4041. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4042. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4043. // Update server certificates using PEM API
  4044. ASSERT_TRUE(
  4045. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.stop();
  4048. }
  4049. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4050. // Start server with client CA (enables client auth)
  4051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4052. ASSERT_TRUE(svr.is_valid());
  4053. bool handler_called = false;
  4054. svr.Get("/test", [&](const Request &req, Response &res) {
  4055. handler_called = true;
  4056. // Verify client certificate is present
  4057. auto cert = req.peer_cert();
  4058. EXPECT_TRUE(static_cast<bool>(cert));
  4059. res.set_content("ok", "text/plain");
  4060. });
  4061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4062. auto se = detail::scope_exit([&] {
  4063. svr.stop();
  4064. t.join();
  4065. ASSERT_FALSE(svr.is_running());
  4066. });
  4067. svr.wait_until_ready();
  4068. // Read PEM files
  4069. std::string cert_pem, key_pem, ca_pem;
  4070. read_file(SERVER_CERT_FILE, cert_pem);
  4071. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4072. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4073. // Update server certificates and client CA using PEM API while server running
  4074. ASSERT_TRUE(
  4075. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4076. // Connect with client certificate
  4077. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4078. cli.enable_server_certificate_verification(false);
  4079. cli.set_connection_timeout(30);
  4080. auto res = cli.Get("/test");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_TRUE(handler_called);
  4084. EXPECT_EQ("ok", res->body);
  4085. }
  4086. // Puts a CA that did not sign the client's certificate in the old one's place.
  4087. static bool replace_client_ca(SSLServer &svr) {
  4088. std::string cert_pem, key_pem, ca_pem;
  4089. read_file(SERVER_CERT_FILE, cert_pem);
  4090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4091. read_file(SERVER_CERT2_FILE, ca_pem);
  4092. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4093. ca_pem.c_str());
  4094. }
  4095. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. svr.Get("/test", [](const Request &, Response &res) {
  4099. res.set_content("ok", "text/plain");
  4100. });
  4101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. auto get = [] {
  4109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4110. cli.enable_server_certificate_verification(false);
  4111. return cli.Get("/test");
  4112. };
  4113. ASSERT_TRUE(get());
  4114. ASSERT_TRUE(replace_client_ca(svr));
  4115. EXPECT_FALSE(get());
  4116. }
  4117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4118. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4120. ASSERT_TRUE(svr.is_valid());
  4121. tls::set_verify_callback(svr.tls_context(),
  4122. [](const tls::VerifyContext &) -> bool {
  4123. throw std::runtime_error("verify");
  4124. });
  4125. svr.Get("/test", [](const Request &, Response &res) {
  4126. res.set_content("ok", "text/plain");
  4127. });
  4128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. t.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. auto get = [] {
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. return cli.Get("/test");
  4139. };
  4140. EXPECT_FALSE(get());
  4141. // The handshake is over, so an update does not wait for it.
  4142. std::string cert_pem, key_pem;
  4143. read_file(SERVER_CERT_FILE, cert_pem);
  4144. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4145. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4146. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4147. return v.preverify_ok;
  4148. });
  4149. auto res = get();
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("ok", res->body);
  4152. }
  4153. #endif
  4154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4155. // Sends each request over a new connection with a client certificate,
  4156. // resuming the session of the one before when there is one.
  4157. class ResumingClient {
  4158. public:
  4159. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4160. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4161. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4162. SSL_FILETYPE_PEM);
  4163. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4164. // callback, not through SSL_get1_session().
  4165. SSL_CTX_set_app_data(ctx_, this);
  4166. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4167. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4168. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4169. auto self = static_cast<ResumingClient *>(
  4170. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4171. SSL_SESSION_free(self->session_);
  4172. self->session_ = session;
  4173. return 1; // Keeps the reference
  4174. });
  4175. }
  4176. ~ResumingClient() {
  4177. SSL_SESSION_free(session_);
  4178. SSL_CTX_free(ctx_);
  4179. }
  4180. // Tells whether the request was answered.
  4181. bool get() {
  4182. auto error = Error::Success;
  4183. auto sock = detail::create_client_socket(
  4184. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4185. /*connection_timeout_sec=*/5, 0,
  4186. /*read_timeout_sec=*/5, 0,
  4187. /*write_timeout_sec=*/5, 0, std::string(), error);
  4188. if (sock == INVALID_SOCKET) { return false; }
  4189. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4190. auto ssl = SSL_new(ctx_);
  4191. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4192. SSL_set_fd(ssl, static_cast<int>(sock));
  4193. if (session_) { SSL_set_session(ssl, session_); }
  4194. if (SSL_connect(ssl) != 1) { return false; }
  4195. reused_ = SSL_session_reused(ssl) == 1;
  4196. // Reading the response also takes in a TLS 1.3 session ticket.
  4197. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4198. "Connection: close\r\n\r\n";
  4199. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4200. std::string res;
  4201. char buf[256];
  4202. int n;
  4203. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4204. res.append(buf, static_cast<size_t>(n));
  4205. }
  4206. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4207. SSL_shutdown(ssl);
  4208. return res.find("200 OK") != std::string::npos;
  4209. }
  4210. // Whether the last connection resumed a session
  4211. bool reused() const { return reused_; }
  4212. private:
  4213. SSL_CTX *ctx_;
  4214. SSL_SESSION *session_ = nullptr;
  4215. bool reused_ = false;
  4216. };
  4217. // A client that resumes its session gets through, but not once the client CA
  4218. // has changed, as a resumed session does not show the certificate again.
  4219. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. svr.Get("/test", [](const Request &, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4226. auto se = detail::scope_exit([&] {
  4227. svr.stop();
  4228. t.join();
  4229. ASSERT_FALSE(svr.is_running());
  4230. });
  4231. svr.wait_until_ready();
  4232. ResumingClient cli;
  4233. ASSERT_TRUE(cli.get());
  4234. ASSERT_TRUE(cli.get());
  4235. EXPECT_TRUE(cli.reused());
  4236. ASSERT_TRUE(replace_client_ca(svr));
  4237. EXPECT_FALSE(cli.get());
  4238. }
  4239. // A resumed session does not show the certificate again, so the server does
  4240. // not resume one with a verify callback to run on it.
  4241. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4243. ASSERT_TRUE(svr.is_valid());
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. svr.Get("/test", [](const Request &, Response &res) {
  4248. res.set_content("ok", "text/plain");
  4249. });
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. auto se = detail::scope_exit([&] {
  4252. svr.stop();
  4253. t.join();
  4254. ASSERT_FALSE(svr.is_running());
  4255. });
  4256. svr.wait_until_ready();
  4257. ResumingClient cli;
  4258. ASSERT_TRUE(cli.get());
  4259. ASSERT_TRUE(cli.get());
  4260. EXPECT_FALSE(cli.reused());
  4261. }
  4262. #endif
  4263. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4264. // wolfSSL shares its session cache between contexts, so a resumed session
  4265. // could carry a client certificate checked against another server's CA, or
  4266. // against a client CA since replaced.
  4267. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. // Trusts a CA that did not sign the client's certificate.
  4271. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4272. ASSERT_TRUE(other.is_valid());
  4273. for (auto s : {&svr, &other}) {
  4274. s->Get("/test", [](const Request &, Response &res) {
  4275. res.set_content("ok", "text/plain");
  4276. });
  4277. }
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4280. auto se = detail::scope_exit([&] {
  4281. other.stop();
  4282. svr.stop();
  4283. t2.join();
  4284. t.join();
  4285. });
  4286. svr.wait_until_ready();
  4287. other.wait_until_ready();
  4288. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4289. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4290. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4291. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4292. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4293. ASSERT_EQ(WOLFSSL_SUCCESS,
  4294. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4295. WOLFSSL_FILETYPE_PEM));
  4296. WOLFSSL_SESSION *session = nullptr;
  4297. auto session_se = detail::scope_exit([&] {
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. });
  4300. // A request over a new connection, resuming `session` when there is one and
  4301. // keeping the connection's own in its place. Tells whether it was answered.
  4302. auto get = [&](int port) {
  4303. auto error = Error::Success;
  4304. auto sock = detail::create_client_socket(
  4305. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4306. /*connection_timeout_sec=*/5, 0,
  4307. /*read_timeout_sec=*/5, 0,
  4308. /*write_timeout_sec=*/5, 0, std::string(), error);
  4309. if (sock == INVALID_SOCKET) { return false; }
  4310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4311. auto ssl = wolfSSL_new(ctx);
  4312. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4313. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4314. if (session) { wolfSSL_set_session(ssl, session); }
  4315. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4316. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4317. "Connection: close\r\n\r\n";
  4318. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4319. std::string res;
  4320. char buf[256];
  4321. int n;
  4322. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4323. res.append(buf, static_cast<size_t>(n));
  4324. }
  4325. wolfSSL_shutdown(ssl);
  4326. if (session) { wolfSSL_SESSION_free(session); }
  4327. session = wolfSSL_get1_session(ssl);
  4328. return res.find("200 OK") != std::string::npos;
  4329. };
  4330. ASSERT_TRUE(get(PORT));
  4331. EXPECT_FALSE(get(PORT + 1));
  4332. ASSERT_TRUE(get(PORT));
  4333. ASSERT_TRUE(replace_client_ca(svr));
  4334. EXPECT_FALSE(get(PORT));
  4335. }
  4336. #endif
  4337. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4339. ASSERT_TRUE(svr.is_valid());
  4340. svr.Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4344. auto se = detail::scope_exit([&] {
  4345. svr.stop();
  4346. t.join();
  4347. ASSERT_FALSE(svr.is_running());
  4348. });
  4349. svr.wait_until_ready();
  4350. // A connection that sends no ClientHello keeps its handshake in progress,
  4351. // once the server has had a moment to start it.
  4352. auto error = Error::Success;
  4353. auto sock = detail::create_client_socket(
  4354. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4355. /*connection_timeout_sec=*/5, 0,
  4356. /*read_timeout_sec=*/5, 0,
  4357. /*write_timeout_sec=*/5, 0, std::string(), error);
  4358. ASSERT_NE(INVALID_SOCKET, sock);
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4360. std::string cert_pem, key_pem;
  4361. read_file(SERVER_CERT_FILE, cert_pem);
  4362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4363. auto update = std::async(std::launch::async, [&]() {
  4364. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4365. });
  4366. EXPECT_EQ(std::future_status::timeout,
  4367. update.wait_for(std::chrono::milliseconds(200)));
  4368. detail::close_socket(sock);
  4369. EXPECT_TRUE(update.get());
  4370. SSLClient cli(HOST, PORT);
  4371. cli.enable_server_certificate_verification(false);
  4372. auto res = cli.Get("/test");
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. #endif
  4377. TEST(ErrorHandlerTest, ContentLength) {
  4378. Server svr;
  4379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4380. res.status = StatusCode::OK_200;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. res.status = 524;
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, PORT);
  4397. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4401. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4402. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4403. }
  4404. }
  4405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4406. TEST(ExceptionTest, WithoutExceptionHandler) {
  4407. Server svr;
  4408. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4409. throw std::runtime_error("exception...");
  4410. });
  4411. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4412. throw std::runtime_error("exception\r\n...");
  4413. });
  4414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4415. auto se = detail::scope_exit([&] {
  4416. svr.stop();
  4417. listen_thread.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. Client cli("localhost", PORT);
  4422. {
  4423. auto res = cli.Get("/exception");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4426. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4427. }
  4428. {
  4429. auto res = cli.Get("/unknown");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. }
  4435. TEST(ExceptionTest, WithExceptionHandler) {
  4436. Server svr;
  4437. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4438. std::exception_ptr ep) {
  4439. EXPECT_FALSE(ep == nullptr);
  4440. try {
  4441. std::rethrow_exception(ep);
  4442. } catch (std::exception &e) {
  4443. EXPECT_EQ("abc", std::string(e.what()));
  4444. } catch (...) {}
  4445. res.status = StatusCode::InternalServerError_500;
  4446. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4447. "text/html"); // <= Content-Length still 13 at this point
  4448. });
  4449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4450. res.set_content("Hello World!\n", "text/plain");
  4451. throw std::runtime_error("abc");
  4452. });
  4453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4454. auto se = detail::scope_exit([&] {
  4455. svr.stop();
  4456. thread.join();
  4457. ASSERT_FALSE(svr.is_running());
  4458. });
  4459. svr.wait_until_ready();
  4460. for (size_t i = 0; i < 10; i++) {
  4461. Client cli(HOST, PORT);
  4462. for (size_t j = 0; j < 100; j++) {
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. cli.set_keep_alive(true);
  4471. for (size_t j = 0; j < 100; j++) {
  4472. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4476. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4478. }
  4479. }
  4480. }
  4481. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4482. Server svr;
  4483. svr.set_exception_handler(
  4484. [](const Request &, Response &res, std::exception_ptr) {
  4485. res.set_content("oops", "text/plain");
  4486. });
  4487. svr.Get("/throw", [](const Request &, Response &) {
  4488. throw std::runtime_error("throw");
  4489. });
  4490. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4491. res.status = StatusCode::Created_201;
  4492. throw std::runtime_error("created-then-throw");
  4493. });
  4494. auto port = svr.bind_to_any_port(HOST);
  4495. ASSERT_GT(port, 0);
  4496. thread t = thread([&] { svr.listen_after_bind(); });
  4497. auto se = detail::scope_exit([&] {
  4498. svr.stop();
  4499. t.join();
  4500. ASSERT_FALSE(svr.is_running());
  4501. });
  4502. svr.wait_until_ready();
  4503. Client cli(HOST, port);
  4504. for (auto path : {"/throw", "/created-then-throw"}) {
  4505. auto res = cli.Get(path);
  4506. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4507. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4508. }
  4509. }
  4510. TEST(ExceptionTest, AndErrorHandler) {
  4511. Server svr;
  4512. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4513. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4514. });
  4515. svr.set_exception_handler(
  4516. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4517. EXPECT_FALSE(ep == nullptr);
  4518. try {
  4519. std::rethrow_exception(ep);
  4520. } catch (std::exception &e) {
  4521. res.set_content(e.what(), "text/html");
  4522. } catch (...) {}
  4523. res.status = StatusCode::InternalServerError_500;
  4524. });
  4525. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4526. throw std::runtime_error("EXCEPTION");
  4527. });
  4528. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4529. res.set_content("ERROR", "text/html");
  4530. res.status = StatusCode::InternalServerError_500;
  4531. });
  4532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4533. auto se = detail::scope_exit([&] {
  4534. svr.stop();
  4535. thread.join();
  4536. ASSERT_FALSE(svr.is_running());
  4537. });
  4538. svr.wait_until_ready();
  4539. Client cli(HOST, PORT);
  4540. {
  4541. auto res = cli.Get("/exception");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4544. EXPECT_EQ("EXCEPTION", res->body);
  4545. }
  4546. {
  4547. auto res = cli.Get("/error");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4550. EXPECT_EQ("ERROR", res->body);
  4551. }
  4552. {
  4553. auto res = cli.Get("/invalid");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4556. EXPECT_EQ("NOT_FOUND", res->body);
  4557. }
  4558. }
  4559. #endif
  4560. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4561. // An exception from a user callback outside process_request()'s try/catch
  4562. // used to unwind into the task queue - which does not catch - and terminate
  4563. // the process. Each test below runs the server on a single worker thread: a
  4564. // guard that catches the exception but still loses the thread would otherwise
  4565. // be hidden by a spare worker serving the follow-up request. Note that a
  4566. // regression here aborts the whole test binary rather than failing one test.
  4567. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4568. Server svr;
  4569. svr.new_task_queue = [] { return new ThreadPool(1); };
  4570. std::atomic<int> reported{0};
  4571. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4572. if (err == Error::UserCallbackException) { reported++; }
  4573. });
  4574. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4575. res.set_content_provider(
  4576. 1024, "text/plain",
  4577. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4578. sink.write("hello", 5);
  4579. throw std::runtime_error("from the content provider");
  4580. });
  4581. });
  4582. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4583. res.set_content("ok", "text/plain");
  4584. });
  4585. auto port = svr.bind_to_any_port(HOST);
  4586. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4587. auto se = detail::scope_exit([&] {
  4588. svr.stop();
  4589. listen_thread.join();
  4590. ASSERT_FALSE(svr.is_running());
  4591. });
  4592. svr.wait_until_ready();
  4593. {
  4594. Client cli(HOST, port);
  4595. cli.set_read_timeout(5, 0);
  4596. EXPECT_FALSE(cli.Get("/throw"));
  4597. }
  4598. EXPECT_TRUE(svr.is_running());
  4599. EXPECT_EQ(1, reported.load());
  4600. // A request on a fresh connection is still served.
  4601. {
  4602. Client cli(HOST, port);
  4603. auto res = cli.Get("/ok");
  4604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. EXPECT_EQ("ok", res->body);
  4607. }
  4608. }
  4609. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4610. Server svr;
  4611. svr.new_task_queue = [] { return new ThreadPool(1); };
  4612. std::atomic<bool> should_throw{true};
  4613. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4614. res.set_content("hi", "text/plain");
  4615. });
  4616. svr.set_post_routing_handler(
  4617. [&](const Request & /*req*/, Response & /*res*/) {
  4618. if (should_throw) {
  4619. throw std::runtime_error("from the post-routing handler");
  4620. }
  4621. });
  4622. auto port = svr.bind_to_any_port(HOST);
  4623. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4624. auto se = detail::scope_exit([&] {
  4625. svr.stop();
  4626. listen_thread.join();
  4627. ASSERT_FALSE(svr.is_running());
  4628. });
  4629. svr.wait_until_ready();
  4630. {
  4631. Client cli(HOST, port);
  4632. cli.set_read_timeout(5, 0);
  4633. EXPECT_FALSE(cli.Get("/hi"));
  4634. }
  4635. EXPECT_TRUE(svr.is_running());
  4636. should_throw = false;
  4637. {
  4638. Client cli(HOST, port);
  4639. auto res = cli.Get("/hi");
  4640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4641. EXPECT_EQ(StatusCode::OK_200, res->status);
  4642. EXPECT_EQ("hi", res->body);
  4643. }
  4644. }
  4645. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4646. // The guard reports the caught exception through the error logger, which is
  4647. // a user callback too. A logger that throws has to be contained as well, or
  4648. // the process would terminate from inside the catch.
  4649. Server svr;
  4650. svr.new_task_queue = [] { return new ThreadPool(1); };
  4651. std::atomic<int> reported{0};
  4652. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4653. if (err == Error::UserCallbackException) {
  4654. reported++;
  4655. throw std::runtime_error("from the error logger");
  4656. }
  4657. });
  4658. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4659. res.set_content_provider(
  4660. 1024, "text/plain",
  4661. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4662. sink.write("hello", 5);
  4663. throw std::runtime_error("from the content provider");
  4664. });
  4665. });
  4666. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4667. res.set_content("ok", "text/plain");
  4668. });
  4669. auto port = svr.bind_to_any_port(HOST);
  4670. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. listen_thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. {
  4678. Client cli(HOST, port);
  4679. cli.set_read_timeout(5, 0);
  4680. EXPECT_FALSE(cli.Get("/throw"));
  4681. }
  4682. EXPECT_TRUE(svr.is_running());
  4683. EXPECT_EQ(1, reported.load());
  4684. {
  4685. Client cli(HOST, port);
  4686. auto res = cli.Get("/ok");
  4687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4688. EXPECT_EQ(StatusCode::OK_200, res->status);
  4689. EXPECT_EQ("ok", res->body);
  4690. }
  4691. }
  4692. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4693. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4694. // so the exception unwinds through the ws::WebSocket object on its way to
  4695. // the guard. None of the HTTP cases above cross that.
  4696. Server svr;
  4697. svr.new_task_queue = [] { return new ThreadPool(1); };
  4698. std::atomic<int> reported{0};
  4699. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4700. if (err == Error::UserCallbackException) { reported++; }
  4701. });
  4702. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4703. throw std::runtime_error("from the WebSocket handler");
  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. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4718. "/ws");
  4719. auto res = client.connect();
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. // The server dropped the connection instead of dying.
  4722. std::string msg;
  4723. EXPECT_FALSE(client.read(msg));
  4724. client.close();
  4725. }
  4726. EXPECT_TRUE(svr.is_running());
  4727. EXPECT_EQ(1, reported.load());
  4728. {
  4729. Client cli(HOST, port);
  4730. auto res = cli.Get("/ok");
  4731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4732. EXPECT_EQ(StatusCode::OK_200, res->status);
  4733. EXPECT_EQ("ok", res->body);
  4734. }
  4735. }
  4736. #ifdef CPPHTTPLIB_SSL_ENABLED
  4737. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4738. // SSLServer::process_and_close_socket() is a separate overload with its own
  4739. // guard, so it is exercised on its own.
  4740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4741. ASSERT_TRUE(svr.is_valid());
  4742. svr.new_task_queue = [] { return new ThreadPool(1); };
  4743. std::atomic<int> reported{0};
  4744. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4745. if (err == Error::UserCallbackException) { reported++; }
  4746. });
  4747. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4748. res.set_content_provider(
  4749. 1024, "text/plain",
  4750. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4751. sink.write("hello", 5);
  4752. throw std::runtime_error("from the content provider");
  4753. });
  4754. });
  4755. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4756. res.set_content("ok", "text/plain");
  4757. });
  4758. auto port = svr.bind_to_any_port(HOST);
  4759. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4760. auto se = detail::scope_exit([&] {
  4761. svr.stop();
  4762. listen_thread.join();
  4763. ASSERT_FALSE(svr.is_running());
  4764. });
  4765. svr.wait_until_ready();
  4766. {
  4767. SSLClient cli(HOST, port);
  4768. cli.enable_server_certificate_verification(false);
  4769. cli.set_read_timeout(5, 0);
  4770. EXPECT_FALSE(cli.Get("/throw"));
  4771. }
  4772. EXPECT_TRUE(svr.is_running());
  4773. EXPECT_EQ(1, reported.load());
  4774. {
  4775. SSLClient cli(HOST, port);
  4776. cli.enable_server_certificate_verification(false);
  4777. auto res = cli.Get("/ok");
  4778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. EXPECT_EQ("ok", res->body);
  4781. }
  4782. }
  4783. #endif
  4784. #endif
  4785. TEST(NoContentTest, ContentLength) {
  4786. Server svr;
  4787. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4788. res.status = StatusCode::NoContent_204;
  4789. });
  4790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4791. auto se = detail::scope_exit([&] {
  4792. svr.stop();
  4793. thread.join();
  4794. ASSERT_FALSE(svr.is_running());
  4795. });
  4796. svr.wait_until_ready();
  4797. {
  4798. Client cli(HOST, PORT);
  4799. auto res = cli.Get("/hi");
  4800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4801. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4802. // RFC 9110 8.6: none in a 204 response
  4803. EXPECT_FALSE(res->has_header("Content-Length"));
  4804. }
  4805. }
  4806. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4807. Server svr;
  4808. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4809. res.set_header("Content-Length", "5");
  4810. res.set_content("hello world", "text/plain");
  4811. });
  4812. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4813. // A body that reads as the last chunk, were it taken as chunked
  4814. res.set_header("Transfer-Encoding", "chunked");
  4815. res.set_content("0\r\n\r\n", "text/plain");
  4816. });
  4817. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4818. res.set_header("Content-Length", "2");
  4819. res.set_content_provider(5, "text/plain",
  4820. [](size_t offset, size_t length, DataSink &sink) {
  4821. sink.write(&"hello"[offset], length);
  4822. return true;
  4823. });
  4824. });
  4825. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4826. res.set_header("Content-Length", "1234");
  4827. });
  4828. thread t = thread([&] { svr.listen(HOST, PORT); });
  4829. auto se = detail::scope_exit([&] {
  4830. svr.stop();
  4831. t.join();
  4832. ASSERT_FALSE(svr.is_running());
  4833. });
  4834. svr.wait_until_ready();
  4835. Client cli(HOST, PORT);
  4836. cli.set_read_timeout(1, 0);
  4837. auto expect_body = [&](const Result &res, const std::string &body) {
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(body, res->body);
  4840. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4841. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4842. };
  4843. Headers identity{{"Accept-Encoding", ""}};
  4844. expect_body(cli.Get("/body", identity), "hello world");
  4845. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4846. expect_body(cli.Get("/body",
  4847. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4848. "he");
  4849. expect_body(cli.Get("/provider", identity), "hello");
  4850. expect_body(cli.Get("/empty", identity), "");
  4851. // A HEAD response may give the length of the body a GET would get.
  4852. auto res = cli.Head("/empty");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4855. }
  4856. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4857. Server svr;
  4858. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4859. res.set_content("short", "text/plain");
  4860. });
  4861. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4862. res.body += " with a footer";
  4863. res.set_header("Transfer-Encoding", "chunked");
  4864. });
  4865. thread t = thread([&] { svr.listen(HOST, PORT); });
  4866. auto se = detail::scope_exit([&] {
  4867. svr.stop();
  4868. t.join();
  4869. ASSERT_FALSE(svr.is_running());
  4870. });
  4871. svr.wait_until_ready();
  4872. Client cli(HOST, PORT);
  4873. cli.set_read_timeout(1, 0);
  4874. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ("short with a footer", res->body);
  4877. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4878. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4879. }
  4880. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4881. Server svr;
  4882. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4883. res.set_header("Content-Length", "3");
  4884. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4885. sink.write("abc", 3);
  4886. sink.done();
  4887. return true;
  4888. });
  4889. });
  4890. thread t = thread([&] { svr.listen(HOST, PORT); });
  4891. auto se = detail::scope_exit([&] {
  4892. svr.stop();
  4893. t.join();
  4894. ASSERT_FALSE(svr.is_running());
  4895. });
  4896. svr.wait_until_ready();
  4897. Client cli(HOST, PORT);
  4898. cli.set_keep_alive(true);
  4899. auto res = cli.Get("/");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ("abc", res->body);
  4902. EXPECT_FALSE(res->has_header("Content-Length"));
  4903. EXPECT_EQ("close", res->get_header_value("Connection"));
  4904. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4905. // No body to delimit
  4906. auto head = cli.Head("/");
  4907. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4908. EXPECT_FALSE(head->has_header("Connection"));
  4909. }
  4910. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4911. #ifdef CPPHTTPLIB_SSL_ENABLED
  4912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4913. ASSERT_TRUE(svr.is_valid());
  4914. #else
  4915. Server svr;
  4916. #endif
  4917. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4918. if (req.path == "/routing_handler") {
  4919. res.set_header("PRE_ROUTING", "on");
  4920. res.set_content("Routing Handler", "text/plain");
  4921. return httplib::Server::HandlerResponse::Handled;
  4922. }
  4923. return httplib::Server::HandlerResponse::Unhandled;
  4924. });
  4925. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4926. res.set_content("Error", "text/html");
  4927. });
  4928. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4929. if (req.path == "/routing_handler") {
  4930. res.set_header("POST_ROUTING", "on");
  4931. }
  4932. });
  4933. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4934. res.set_content("Hello World!\n", "text/plain");
  4935. });
  4936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. {
  4944. #ifdef CPPHTTPLIB_SSL_ENABLED
  4945. SSLClient cli(HOST, PORT);
  4946. cli.enable_server_certificate_verification(false);
  4947. #else
  4948. Client cli(HOST, PORT);
  4949. #endif
  4950. auto res = cli.Get("/routing_handler");
  4951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4952. EXPECT_EQ(StatusCode::OK_200, res->status);
  4953. EXPECT_EQ("Routing Handler", res->body);
  4954. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4955. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4956. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4957. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4958. }
  4959. {
  4960. #ifdef CPPHTTPLIB_SSL_ENABLED
  4961. SSLClient cli(HOST, PORT);
  4962. cli.enable_server_certificate_verification(false);
  4963. #else
  4964. Client cli(HOST, PORT);
  4965. #endif
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("Hello World!\n", res->body);
  4970. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4971. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4972. }
  4973. {
  4974. #ifdef CPPHTTPLIB_SSL_ENABLED
  4975. SSLClient cli(HOST, PORT);
  4976. cli.enable_server_certificate_verification(false);
  4977. #else
  4978. Client cli(HOST, PORT);
  4979. #endif
  4980. auto res = cli.Get("/aaa");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4983. EXPECT_EQ("Error", res->body);
  4984. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4985. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4986. }
  4987. }
  4988. TEST(RequestHandlerTest, PreRequestHandler) {
  4989. auto route_path = "/user/:user";
  4990. Server svr;
  4991. svr.Get("/hi", [](const Request &, Response &res) {
  4992. res.set_content("hi", "text/plain");
  4993. });
  4994. svr.Get(route_path, [](const Request &req, Response &res) {
  4995. res.set_content(req.path_params.at("user"), "text/plain");
  4996. });
  4997. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4998. if (req.matched_route == route_path) {
  4999. auto user = req.path_params.at("user");
  5000. if (user != "john") {
  5001. res.status = StatusCode::Forbidden_403;
  5002. res.set_content("error", "text/html");
  5003. return Server::HandlerResponse::Handled;
  5004. }
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. {
  5017. auto res = cli.Get("/hi");
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. EXPECT_EQ("hi", res->body);
  5021. }
  5022. {
  5023. auto res = cli.Get("/user/john");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("john", res->body);
  5027. }
  5028. {
  5029. auto res = cli.Get("/user/invalid-user");
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5032. EXPECT_EQ("error", res->body);
  5033. }
  5034. }
  5035. // The pre-request handler must run before the request body is read, so a
  5036. // rejected request never forces the server to buffer a (potentially large)
  5037. // body. Here the posted body is larger than the payload limit: if the body
  5038. // were read first the server would answer 413, but because the pre-request
  5039. // handler runs first it answers 403 and the body is never read.
  5040. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5041. Server svr;
  5042. svr.set_payload_max_length(8);
  5043. auto handler_ran = false;
  5044. svr.Post("/reject", [&](const Request &req, Response &res) {
  5045. handler_ran = true;
  5046. res.set_content(req.body, "text/plain");
  5047. });
  5048. svr.Post("/accept", [](const Request &req, Response &res) {
  5049. res.set_content(req.body, "text/plain");
  5050. });
  5051. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5052. if (req.matched_route == "/reject") {
  5053. res.status = StatusCode::Forbidden_403;
  5054. res.set_content("denied", "text/plain");
  5055. return Server::HandlerResponse::Handled;
  5056. }
  5057. return Server::HandlerResponse::Unhandled;
  5058. });
  5059. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5060. auto se = detail::scope_exit([&] {
  5061. svr.stop();
  5062. thread.join();
  5063. ASSERT_FALSE(svr.is_running());
  5064. });
  5065. svr.wait_until_ready();
  5066. Client cli(HOST, PORT);
  5067. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5068. // rejects with 403 before the body is read, so 413 is never reached.
  5069. {
  5070. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5073. EXPECT_EQ("denied", res->body);
  5074. EXPECT_FALSE(handler_ran);
  5075. }
  5076. // An approved route still reads the body and enforces the payload limit.
  5077. {
  5078. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5081. }
  5082. }
  5083. TEST(UserDataTest, BasicOperations) {
  5084. httplib::UserData ud;
  5085. // Initially empty
  5086. EXPECT_FALSE(ud.has("key"));
  5087. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5088. // set and get
  5089. ud.set("key", 42);
  5090. EXPECT_TRUE(ud.has("key"));
  5091. auto *p = ud.get<int>("key");
  5092. ASSERT_NE(nullptr, p);
  5093. EXPECT_EQ(42, *p);
  5094. // Type mismatch → nullptr
  5095. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5096. // Overwrite with different type
  5097. ud.set("key", std::string("hello"));
  5098. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5099. auto *s = ud.get<std::string>("key");
  5100. ASSERT_NE(nullptr, s);
  5101. EXPECT_EQ("hello", *s);
  5102. // erase
  5103. ud.erase("key");
  5104. EXPECT_FALSE(ud.has("key"));
  5105. // clear
  5106. ud.set("a", 1);
  5107. ud.set("b", 2);
  5108. ud.clear();
  5109. EXPECT_FALSE(ud.has("a"));
  5110. EXPECT_FALSE(ud.has("b"));
  5111. }
  5112. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5113. struct AuthCtx {
  5114. std::string user_id;
  5115. };
  5116. Server svr;
  5117. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5118. res.user_data.set("auth", AuthCtx{"alice"});
  5119. return Server::HandlerResponse::Unhandled;
  5120. });
  5121. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5122. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5123. ASSERT_NE(nullptr, ctx);
  5124. res.set_content("Hello " + ctx->user_id, "text/plain");
  5125. });
  5126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5127. auto se = detail::scope_exit([&] {
  5128. svr.stop();
  5129. thread.join();
  5130. ASSERT_FALSE(svr.is_running());
  5131. });
  5132. svr.wait_until_ready();
  5133. Client cli(HOST, PORT);
  5134. auto res = cli.Get("/me");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. EXPECT_EQ("Hello alice", res->body);
  5138. }
  5139. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5140. struct RoleCtx {
  5141. std::string role;
  5142. };
  5143. Server svr;
  5144. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5145. res.user_data.set("role", RoleCtx{"admin"});
  5146. return Server::HandlerResponse::Unhandled;
  5147. });
  5148. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5149. auto *ctx = res.user_data.get<RoleCtx>("role");
  5150. ASSERT_NE(nullptr, ctx);
  5151. res.set_content(ctx->role, "text/plain");
  5152. });
  5153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5154. auto se = detail::scope_exit([&] {
  5155. svr.stop();
  5156. thread.join();
  5157. ASSERT_FALSE(svr.is_running());
  5158. });
  5159. svr.wait_until_ready();
  5160. Client cli(HOST, PORT);
  5161. auto res = cli.Get("/role");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. EXPECT_EQ("admin", res->body);
  5165. }
  5166. TEST(InvalidFormatTest, StatusCode) {
  5167. Server svr;
  5168. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5169. res.set_content("Hello World!\n", "text/plain");
  5170. res.status = 9999; // Status should be a three-digit code...
  5171. });
  5172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5173. auto se = detail::scope_exit([&] {
  5174. svr.stop();
  5175. thread.join();
  5176. ASSERT_FALSE(svr.is_running());
  5177. });
  5178. svr.wait_until_ready();
  5179. {
  5180. Client cli(HOST, PORT);
  5181. auto res = cli.Get("/hi");
  5182. ASSERT_FALSE(res);
  5183. }
  5184. }
  5185. TEST(URLFragmentTest, WithFragment) {
  5186. Server svr;
  5187. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5188. EXPECT_TRUE(req.target == "/hi");
  5189. });
  5190. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5191. auto se = detail::scope_exit([&] {
  5192. svr.stop();
  5193. thread.join();
  5194. ASSERT_FALSE(svr.is_running());
  5195. });
  5196. svr.wait_until_ready();
  5197. {
  5198. Client cli(HOST, PORT);
  5199. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5200. EXPECT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::OK_200, res->status);
  5202. res = cli.Get("/hi%23key1=val1=key2=val2");
  5203. EXPECT_TRUE(res);
  5204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5205. }
  5206. }
  5207. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5208. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5209. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5210. Server svr;
  5211. std::vector<std::string> targets;
  5212. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5213. targets.push_back(req.target);
  5214. });
  5215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. thread.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. Client cli(HOST, PORT);
  5223. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5224. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5225. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5226. // A '?' after the '#' belongs to the fragment, not to the query.
  5227. Request req;
  5228. req.method = "GET";
  5229. req.path = "/hi#f?x=1";
  5230. req.params.emplace("a", "1");
  5231. Response res;
  5232. auto error = Error::Success;
  5233. EXPECT_TRUE(cli.send(req, res, error));
  5234. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5235. "/hi?a=1"}),
  5236. targets);
  5237. }
  5238. TEST(HeaderWriter, SetHeaderWriter) {
  5239. Server svr;
  5240. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5241. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5242. return detail::write_headers(strm, hdrs);
  5243. });
  5244. svr.Get("/hi", [](const Request &req, Response &res) {
  5245. auto it = req.headers.find("CustomClientHeader");
  5246. EXPECT_TRUE(it != req.headers.end());
  5247. EXPECT_EQ(it->second, "CustomClientValue");
  5248. res.set_content("Hello World!\n", "text/plain");
  5249. });
  5250. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5251. auto se = detail::scope_exit([&] {
  5252. svr.stop();
  5253. thread.join();
  5254. ASSERT_FALSE(svr.is_running());
  5255. });
  5256. svr.wait_until_ready();
  5257. {
  5258. Client cli(HOST, PORT);
  5259. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5260. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5261. return detail::write_headers(strm, hdrs);
  5262. });
  5263. auto res = cli.Get("/hi");
  5264. EXPECT_TRUE(res);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. auto it = res->headers.find("CustomServerHeader");
  5267. EXPECT_TRUE(it != res->headers.end());
  5268. EXPECT_EQ(it->second, "CustomServerValue");
  5269. }
  5270. }
  5271. class ServerTest : public ::testing::Test {
  5272. protected:
  5273. ServerTest()
  5274. : cli_(HOST, PORT)
  5275. #ifdef CPPHTTPLIB_SSL_ENABLED
  5276. ,
  5277. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5278. #endif
  5279. {
  5280. #ifdef CPPHTTPLIB_SSL_ENABLED
  5281. cli_.enable_server_certificate_verification(false);
  5282. #endif
  5283. // Allow LARGE_DATA (100MB) responses
  5284. cli_.set_payload_max_length(200 * 1024 * 1024);
  5285. }
  5286. virtual void SetUp() {
  5287. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5288. svr_.set_payload_max_length(200 * 1024 * 1024);
  5289. svr_.set_mount_point("/", "./www");
  5290. svr_.set_mount_point("/mount", "./www2");
  5291. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5292. svr_.Get("/hi",
  5293. [&](const Request & /*req*/, Response &res) {
  5294. res.set_content("Hello World!", "text/plain");
  5295. })
  5296. .Get("/file_content",
  5297. [&](const Request & /*req*/, Response &res) {
  5298. res.set_file_content("./www/dir/test.html");
  5299. })
  5300. .Get("/file_content_with_content_type",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_file_content("./www/file", "text/plain");
  5303. })
  5304. .Get("/invalid_file_content",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. res.set_file_content("./www/dir/invalid_file_path");
  5307. })
  5308. .Get("/http_response_splitting",
  5309. [&](const Request & /*req*/, Response &res) {
  5310. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5311. EXPECT_EQ(0U, res.headers.size());
  5312. EXPECT_FALSE(res.has_header("a"));
  5313. res.set_header("a", "1\nSet-Cookie: a=1");
  5314. EXPECT_EQ(0U, res.headers.size());
  5315. EXPECT_FALSE(res.has_header("a"));
  5316. res.set_header("a", "1\rSet-Cookie: a=1");
  5317. EXPECT_EQ(0U, res.headers.size());
  5318. EXPECT_FALSE(res.has_header("a"));
  5319. res.set_header("a\r\nb", "0");
  5320. EXPECT_EQ(0U, res.headers.size());
  5321. EXPECT_FALSE(res.has_header("a"));
  5322. res.set_header("a\rb", "0");
  5323. EXPECT_EQ(0U, res.headers.size());
  5324. EXPECT_FALSE(res.has_header("a"));
  5325. res.set_header("a\nb", "0");
  5326. EXPECT_EQ(0U, res.headers.size());
  5327. EXPECT_FALSE(res.has_header("a"));
  5328. res.set_redirect("1\r\nSet-Cookie: a=1");
  5329. EXPECT_EQ(0U, res.headers.size());
  5330. EXPECT_FALSE(res.has_header("Location"));
  5331. })
  5332. .Get("/slow",
  5333. [&](const Request & /*req*/, Response &res) {
  5334. std::this_thread::sleep_for(std::chrono::seconds(4));
  5335. res.set_content("slow", "text/plain");
  5336. })
  5337. #if 0
  5338. .Post("/slowpost",
  5339. [&](const Request & /*req*/, Response &res) {
  5340. std::this_thread::sleep_for(std::chrono::seconds(2));
  5341. res.set_content("slow", "text/plain");
  5342. })
  5343. #endif
  5344. .Get("/remote_addr",
  5345. [&](const Request &req, Response &res) {
  5346. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5347. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5348. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5349. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5350. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5351. #endif
  5352. res.set_content(req.remote_addr, "text/plain");
  5353. })
  5354. .Get("/local_addr",
  5355. [&](const Request &req, Response &res) {
  5356. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5357. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5358. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5359. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5360. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5361. #endif
  5362. auto local_addr = req.local_addr;
  5363. auto local_port = std::to_string(req.local_port);
  5364. res.set_content(local_addr.append(":").append(local_port),
  5365. "text/plain");
  5366. })
  5367. .Get("/endwith%",
  5368. [&](const Request & /*req*/, Response &res) {
  5369. res.set_content("Hello World!", "text/plain");
  5370. })
  5371. .Get("/a\\+\\+b",
  5372. [&](const Request &req, Response &res) {
  5373. ASSERT_TRUE(req.has_param("a +b"));
  5374. auto val = req.get_param_value("a +b");
  5375. res.set_content(val, "text/plain");
  5376. })
  5377. .Get("/", [&](const Request & /*req*/,
  5378. Response &res) { res.set_redirect("/hi"); })
  5379. .Post("/1",
  5380. [](const Request & /*req*/, Response &res) {
  5381. res.set_redirect("/2", StatusCode::SeeOther_303);
  5382. })
  5383. .Get("/2",
  5384. [](const Request & /*req*/, Response &res) {
  5385. res.set_content("redirected.", "text/plain");
  5386. res.status = StatusCode::OK_200;
  5387. })
  5388. .Post("/person",
  5389. [&](const Request &req, Response &res) {
  5390. if (req.has_param("name") && req.has_param("note")) {
  5391. persons_[req.get_param_value("name")] =
  5392. req.get_param_value("note");
  5393. } else {
  5394. res.status = StatusCode::BadRequest_400;
  5395. }
  5396. })
  5397. .Put("/person",
  5398. [&](const Request &req, Response &res) {
  5399. if (req.has_param("name") && req.has_param("note")) {
  5400. persons_[req.get_param_value("name")] =
  5401. req.get_param_value("note");
  5402. } else {
  5403. res.status = StatusCode::BadRequest_400;
  5404. }
  5405. })
  5406. .Get("/person/(.*)",
  5407. [&](const Request &req, Response &res) {
  5408. string name = req.matches[1];
  5409. if (persons_.find(name) != persons_.end()) {
  5410. auto note = persons_[name];
  5411. res.set_content(note, "text/plain");
  5412. } else {
  5413. res.status = StatusCode::NotFound_404;
  5414. }
  5415. })
  5416. .Delete("/person",
  5417. [&](const Request &req, Response &res) {
  5418. if (req.has_param("name")) {
  5419. string name = req.get_param_value("name");
  5420. if (persons_.find(name) != persons_.end()) {
  5421. persons_.erase(name);
  5422. res.set_content("DELETED", "text/plain");
  5423. } else {
  5424. res.status = StatusCode::NotFound_404;
  5425. }
  5426. } else {
  5427. res.status = StatusCode::BadRequest_400;
  5428. }
  5429. })
  5430. .Post("/x-www-form-urlencoded-json",
  5431. [&](const Request &req, Response &res) {
  5432. auto json = req.get_param_value("json");
  5433. ASSERT_EQ(JSON_DATA, json);
  5434. res.set_content(json, "appliation/json");
  5435. res.status = StatusCode::OK_200;
  5436. })
  5437. .Get("/streamed-chunked",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. res.set_chunked_content_provider(
  5440. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5441. sink.os << "123";
  5442. sink.os << "456";
  5443. sink.os << "789";
  5444. sink.done();
  5445. return true;
  5446. });
  5447. })
  5448. .Get("/streamed-chunked-with-prohibited-trailer",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. auto i = new int(0);
  5451. // Declare both a prohibited trailer (Content-Length) and an
  5452. // allowed one
  5453. res.set_header("Trailer", "Content-Length, X-Allowed");
  5454. res.set_chunked_content_provider(
  5455. "text/plain",
  5456. [i](size_t /*offset*/, DataSink &sink) {
  5457. switch (*i) {
  5458. case 0: sink.os << "123"; break;
  5459. case 1: sink.os << "456"; break;
  5460. case 2: sink.os << "789"; break;
  5461. case 3: {
  5462. sink.done_with_trailer(
  5463. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5464. } break;
  5465. }
  5466. (*i)++;
  5467. return true;
  5468. },
  5469. [i](bool success) {
  5470. EXPECT_TRUE(success);
  5471. delete i;
  5472. });
  5473. })
  5474. .Get("/streamed-chunked2",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. auto i = new int(0);
  5477. res.set_chunked_content_provider(
  5478. "text/plain",
  5479. [i](size_t /*offset*/, DataSink &sink) {
  5480. switch (*i) {
  5481. case 0: sink.os << "123"; break;
  5482. case 1: sink.os << "456"; break;
  5483. case 2: sink.os << "789"; break;
  5484. case 3: sink.done(); break;
  5485. }
  5486. (*i)++;
  5487. return true;
  5488. },
  5489. [i](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete i;
  5492. });
  5493. })
  5494. .Get("/streamed-chunked-with-trailer",
  5495. [&](const Request & /*req*/, Response &res) {
  5496. auto i = new int(0);
  5497. res.set_header("Trailer", "Dummy1, Dummy2");
  5498. res.set_chunked_content_provider(
  5499. "text/plain",
  5500. [i](size_t /*offset*/, DataSink &sink) {
  5501. switch (*i) {
  5502. case 0: sink.os << "123"; break;
  5503. case 1: sink.os << "456"; break;
  5504. case 2: sink.os << "789"; break;
  5505. case 3: {
  5506. sink.done_with_trailer(
  5507. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5508. } break;
  5509. }
  5510. (*i)++;
  5511. return true;
  5512. },
  5513. [i](bool success) {
  5514. EXPECT_TRUE(success);
  5515. delete i;
  5516. });
  5517. })
  5518. .Get("/streamed",
  5519. [&](const Request & /*req*/, Response &res) {
  5520. res.set_content_provider(
  5521. 6, "text/plain",
  5522. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5523. sink.os << (offset < 3 ? "a" : "b");
  5524. return true;
  5525. });
  5526. })
  5527. .Get("/streamed-without-length",
  5528. [&](const Request & /*req*/, Response &res) {
  5529. auto data = new std::string("abcdefg");
  5530. res.set_content_provider(
  5531. "text/plain",
  5532. [data](size_t offset, DataSink &sink) {
  5533. if (offset < data->size()) {
  5534. sink.os << data->substr(offset);
  5535. }
  5536. sink.done();
  5537. return true;
  5538. },
  5539. [data](bool success) {
  5540. EXPECT_TRUE(success);
  5541. delete data;
  5542. });
  5543. })
  5544. .Get("/streamed-with-range",
  5545. [&](const Request &req, Response &res) {
  5546. auto data = new std::string("abcdefg");
  5547. // An explicit status keeps the server from picking the 206 it
  5548. // would otherwise choose for a ranged request, so the response
  5549. // is not a partial representation.
  5550. auto status = req.get_param_value("status");
  5551. if (status == "200") {
  5552. res.status = StatusCode::OK_200;
  5553. } else if (status == "403") {
  5554. res.status = StatusCode::Forbidden_403;
  5555. }
  5556. res.set_content_provider(
  5557. data->size(), "text/plain",
  5558. [data](size_t offset, size_t length, DataSink &sink) {
  5559. size_t DATA_CHUNK_SIZE = 4;
  5560. const auto &d = *data;
  5561. auto out_len =
  5562. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5563. auto ret =
  5564. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5565. EXPECT_TRUE(ret);
  5566. return true;
  5567. },
  5568. [data, &req](bool success) {
  5569. EXPECT_EQ(success, !req.has_param("error"));
  5570. delete data;
  5571. });
  5572. })
  5573. .Get("/streamed-cancel",
  5574. [&](const Request & /*req*/, Response &res) {
  5575. res.set_content_provider(
  5576. size_t(-1), "text/plain",
  5577. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5578. sink.os << "data_chunk";
  5579. return true;
  5580. });
  5581. })
  5582. .Get("/regex-with-delimiter",
  5583. [&](const Request &req, Response & /*res*/) {
  5584. ASSERT_TRUE(req.has_param("key"));
  5585. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5586. })
  5587. .Get("/with-range",
  5588. [&](const Request & /*req*/, Response &res) {
  5589. res.set_content("abcdefg", "text/plain");
  5590. })
  5591. .Get("/test-start-time",
  5592. [&](const Request &req, Response & /*res*/) {
  5593. EXPECT_NE(req.start_time_,
  5594. std::chrono::steady_clock::time_point::min());
  5595. })
  5596. .Get("/with-range-customized-response",
  5597. [&](const Request & /*req*/, Response &res) {
  5598. res.status = StatusCode::BadRequest_400;
  5599. res.set_content(JSON_DATA, "application/json");
  5600. })
  5601. .Post("/chunked",
  5602. [&](const Request &req, Response & /*res*/) {
  5603. EXPECT_EQ(req.body, "dechunked post body");
  5604. })
  5605. .Post("/large-chunked",
  5606. [&](const Request &req, Response & /*res*/) {
  5607. std::string expected(6 * 30 * 1024u, 'a');
  5608. EXPECT_EQ(req.body, expected);
  5609. })
  5610. .Post("/multipart",
  5611. [&](const Request &req, Response & /*res*/) {
  5612. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5613. req.form.get_field_count("text2") +
  5614. req.form.get_field_count("file3") +
  5615. req.form.get_field_count("file4"));
  5616. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5617. req.form.get_file_count("file2"));
  5618. ASSERT_TRUE(!req.form.has_file("???"));
  5619. ASSERT_TRUE(!req.form.has_field("???"));
  5620. ASSERT_TRUE(req.body.empty());
  5621. {
  5622. const auto &text = req.form.get_field("text1");
  5623. EXPECT_EQ("text default", text);
  5624. }
  5625. {
  5626. const auto &text = req.form.get_field("text2");
  5627. EXPECT_EQ("aωb", text);
  5628. }
  5629. {
  5630. const auto &file = req.form.get_file("file1");
  5631. EXPECT_EQ("hello.txt", file.filename);
  5632. EXPECT_EQ("text/plain", file.content_type);
  5633. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5634. }
  5635. {
  5636. const auto &file = req.form.get_file("file2");
  5637. EXPECT_EQ("world.json", file.filename);
  5638. EXPECT_EQ("application/json", file.content_type);
  5639. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5640. }
  5641. {
  5642. const auto &text = req.form.get_field("file3");
  5643. EXPECT_EQ(0u, text.size());
  5644. }
  5645. {
  5646. const auto &text = req.form.get_field("file4");
  5647. EXPECT_EQ(0u, text.size());
  5648. }
  5649. })
  5650. .Post("/multipart/multi_file_values",
  5651. [&](const Request &req, Response & /*res*/) {
  5652. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5653. req.form.get_field_count("multi_text1"));
  5654. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5655. ASSERT_TRUE(!req.form.has_file("???"));
  5656. ASSERT_TRUE(!req.form.has_field("???"));
  5657. ASSERT_TRUE(req.body.empty());
  5658. {
  5659. const auto &text = req.form.get_field("text");
  5660. EXPECT_EQ("default text", text);
  5661. }
  5662. {
  5663. const auto &text1_values = req.form.get_fields("multi_text1");
  5664. EXPECT_EQ(2u, text1_values.size());
  5665. EXPECT_EQ("aaaaa", text1_values[0]);
  5666. EXPECT_EQ("bbbbb", text1_values[1]);
  5667. }
  5668. {
  5669. const auto &file1_values = req.form.get_files("multi_file1");
  5670. EXPECT_EQ(2u, file1_values.size());
  5671. auto file1 = file1_values[0];
  5672. EXPECT_EQ(file1.filename, "hello.txt");
  5673. EXPECT_EQ(file1.content_type, "text/plain");
  5674. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5675. auto file2 = file1_values[1];
  5676. EXPECT_EQ(file2.filename, "world.json");
  5677. EXPECT_EQ(file2.content_type, "application/json");
  5678. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5679. }
  5680. })
  5681. .Post("/empty",
  5682. [&](const Request &req, Response &res) {
  5683. EXPECT_EQ(req.body, "");
  5684. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5685. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5686. res.set_content("empty", "text/plain");
  5687. })
  5688. .Post("/empty-no-content-type",
  5689. [&](const Request &req, Response &res) {
  5690. EXPECT_EQ(req.body, "");
  5691. EXPECT_FALSE(req.has_header("Content-Type"));
  5692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5693. res.set_content("empty-no-content-type", "text/plain");
  5694. })
  5695. .Post("/path-only",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("path-only", "text/plain");
  5701. })
  5702. .Post("/path-headers-only",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "");
  5705. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5706. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5707. EXPECT_EQ("world", req.get_header_value("hello"));
  5708. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5709. res.set_content("path-headers-only", "text/plain");
  5710. })
  5711. .Post("/post-large",
  5712. [&](const Request &req, Response &res) {
  5713. EXPECT_EQ(req.body, LARGE_DATA);
  5714. res.set_content(req.body, "text/plain");
  5715. })
  5716. .Post("/post-loopback",
  5717. [&](const Request &, Response &res,
  5718. ContentReader const &content_reader) {
  5719. std::string body;
  5720. content_reader([&](const char *data, size_t data_length) {
  5721. body.append(data, data_length);
  5722. return true;
  5723. });
  5724. res.set_content(body, "text/plain");
  5725. })
  5726. .Put("/put-loopback",
  5727. [&](const Request &, Response &res,
  5728. ContentReader const &content_reader) {
  5729. std::string body;
  5730. content_reader([&](const char *data, size_t data_length) {
  5731. body.append(data, data_length);
  5732. return true;
  5733. });
  5734. res.set_content(body, "text/plain");
  5735. })
  5736. .Patch("/patch-loopback",
  5737. [&](const Request &, Response &res,
  5738. ContentReader const &content_reader) {
  5739. std::string body;
  5740. content_reader([&](const char *data, size_t data_length) {
  5741. body.append(data, data_length);
  5742. return true;
  5743. });
  5744. res.set_content(body, "text/plain");
  5745. })
  5746. .Put("/empty-no-content-type",
  5747. [&](const Request &req, Response &res) {
  5748. EXPECT_EQ(req.body, "");
  5749. EXPECT_FALSE(req.has_header("Content-Type"));
  5750. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5751. res.set_content("empty-no-content-type", "text/plain");
  5752. })
  5753. .Put("/put",
  5754. [&](const Request &req, Response &res) {
  5755. EXPECT_EQ(req.body, "PUT");
  5756. res.set_content(req.body, "text/plain");
  5757. })
  5758. .Put("/put-large",
  5759. [&](const Request &req, Response &res) {
  5760. EXPECT_EQ(req.body, LARGE_DATA);
  5761. res.set_content(req.body, "text/plain");
  5762. })
  5763. .Patch("/patch",
  5764. [&](const Request &req, Response &res) {
  5765. EXPECT_EQ(req.body, "PATCH");
  5766. res.set_content(req.body, "text/plain");
  5767. })
  5768. .Delete("/delete",
  5769. [&](const Request & /*req*/, Response &res) {
  5770. res.set_content("DELETE", "text/plain");
  5771. })
  5772. .Delete("/delete-body",
  5773. [&](const Request &req, Response &res) {
  5774. EXPECT_EQ(req.body, "content");
  5775. res.set_content(req.body, "text/plain");
  5776. })
  5777. .Options(R"(\*)",
  5778. [&](const Request & /*req*/, Response &res) {
  5779. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5780. })
  5781. .CustomRoute("PROPFIND", "/dav/:id",
  5782. [&](const Request &req, Response &res) {
  5783. res.set_header("x-body-size",
  5784. std::to_string(req.body.size()));
  5785. res.set_header("x-matched-route", req.matched_route);
  5786. res.set_header("x-dav-id", req.path_params.at("id"));
  5787. res.status = StatusCode::MultiStatus_207;
  5788. res.set_content(req.body, "application/xml");
  5789. })
  5790. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5791. [&](const Request &req, Response &res) {
  5792. res.set_header("x-dav-match", req.matches[1]);
  5793. res.status = StatusCode::MultiStatus_207;
  5794. })
  5795. .CustomRoute("MKCOL", "/dav-mkcol",
  5796. [&](const Request &req, Response &res) {
  5797. EXPECT_TRUE(req.body.empty());
  5798. res.status = StatusCode::Created_201;
  5799. })
  5800. .CustomRoute(
  5801. "REPORT", "/dav-report",
  5802. [&](const Request & /*req*/, Response &res,
  5803. const ContentReader &content_reader) {
  5804. std::string body;
  5805. content_reader([&](const char *data, size_t data_length) {
  5806. body.append(data, data_length);
  5807. return true;
  5808. });
  5809. res.set_header("x-body-size", std::to_string(body.size()));
  5810. res.status = StatusCode::MultiStatus_207;
  5811. res.set_content(body, "application/xml");
  5812. })
  5813. .Get("/request-target",
  5814. [&](const Request &req, Response & /*res*/) {
  5815. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5816. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5817. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5818. })
  5819. .Get("/long-query-value",
  5820. [&](const Request &req, Response & /*res*/) {
  5821. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5822. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5823. })
  5824. .Get("/too-long-query-value",
  5825. [&](const Request &req, Response & /*res*/) {
  5826. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5827. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5828. })
  5829. .Get("/array-param",
  5830. [&](const Request &req, Response & /*res*/) {
  5831. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5832. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5833. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5834. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5835. })
  5836. .Get("/array-param-values",
  5837. [&](const Request &req, Response & /*res*/) {
  5838. auto values = req.get_param_values("array");
  5839. EXPECT_EQ(3u, values.size());
  5840. EXPECT_EQ("value1", values[0]);
  5841. EXPECT_EQ("value2", values[1]);
  5842. EXPECT_EQ("value3", values[2]);
  5843. auto empty = req.get_param_values("nonexistent");
  5844. EXPECT_TRUE(empty.empty());
  5845. })
  5846. .Post("/validate-no-multiple-headers",
  5847. [&](const Request &req, Response & /*res*/) {
  5848. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5849. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5850. })
  5851. .Post("/content_receiver",
  5852. [&](const Request &req, Response &res,
  5853. const ContentReader &content_reader) {
  5854. if (req.is_multipart_form_data()) {
  5855. std::vector<FormData> items;
  5856. content_reader(
  5857. [&](const FormData &file) {
  5858. items.push_back(file);
  5859. return true;
  5860. },
  5861. [&](const char *data, size_t data_length) {
  5862. items.back().content.append(data, data_length);
  5863. return true;
  5864. });
  5865. EXPECT_EQ(5u, items.size());
  5866. {
  5867. const auto &file = get_file_value(items, "text1");
  5868. EXPECT_TRUE(file.filename.empty());
  5869. EXPECT_EQ("text default", file.content);
  5870. }
  5871. {
  5872. const auto &file = get_file_value(items, "text2");
  5873. EXPECT_TRUE(file.filename.empty());
  5874. EXPECT_EQ("aωb", file.content);
  5875. }
  5876. {
  5877. const auto &file = get_file_value(items, "file1");
  5878. EXPECT_EQ("hello.txt", file.filename);
  5879. EXPECT_EQ("text/plain", file.content_type);
  5880. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5881. }
  5882. {
  5883. const auto &file = get_file_value(items, "file2");
  5884. EXPECT_EQ("world.json", file.filename);
  5885. EXPECT_EQ("application/json", file.content_type);
  5886. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5887. }
  5888. {
  5889. const auto &file = get_file_value(items, "file3");
  5890. EXPECT_TRUE(file.filename.empty());
  5891. EXPECT_EQ("application/octet-stream", file.content_type);
  5892. EXPECT_EQ(0u, file.content.size());
  5893. }
  5894. } else {
  5895. std::string body;
  5896. content_reader([&](const char *data, size_t data_length) {
  5897. EXPECT_EQ(7U, data_length);
  5898. body.append(data, data_length);
  5899. return true;
  5900. });
  5901. EXPECT_EQ(body, "content");
  5902. res.set_content(body, "text/plain");
  5903. }
  5904. })
  5905. .Put("/content_receiver",
  5906. [&](const Request & /*req*/, Response &res,
  5907. const ContentReader &content_reader) {
  5908. std::string body;
  5909. content_reader([&](const char *data, size_t data_length) {
  5910. body.append(data, data_length);
  5911. return true;
  5912. });
  5913. EXPECT_EQ(body, "content");
  5914. res.set_content(body, "text/plain");
  5915. })
  5916. .Patch("/content_receiver",
  5917. [&](const Request & /*req*/, Response &res,
  5918. const ContentReader &content_reader) {
  5919. std::string body;
  5920. content_reader([&](const char *data, size_t data_length) {
  5921. body.append(data, data_length);
  5922. return true;
  5923. });
  5924. EXPECT_EQ(body, "content");
  5925. res.set_content(body, "text/plain");
  5926. })
  5927. .Post("/query-string-and-body",
  5928. [&](const Request &req, Response & /*res*/) {
  5929. ASSERT_TRUE(req.has_param("key"));
  5930. EXPECT_EQ(req.get_param_value("key"), "value");
  5931. EXPECT_EQ(req.body, "content");
  5932. })
  5933. .Get("/last-request",
  5934. [&](const Request &req, Response & /*res*/) {
  5935. EXPECT_EQ("close", req.get_header_value("Connection"));
  5936. })
  5937. .Get(R"(/redirect/(\d+))",
  5938. [&](const Request &req, Response &res) {
  5939. auto num = std::stoi(req.matches[1]) + 1;
  5940. std::string url = "/redirect/" + std::to_string(num);
  5941. res.set_redirect(url);
  5942. })
  5943. .Post("/binary",
  5944. [&](const Request &req, Response &res) {
  5945. EXPECT_EQ(4U, req.body.size());
  5946. EXPECT_EQ("application/octet-stream",
  5947. req.get_header_value("Content-Type"));
  5948. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5949. res.set_content(req.body, "application/octet-stream");
  5950. })
  5951. .Put("/binary",
  5952. [&](const Request &req, Response &res) {
  5953. EXPECT_EQ(4U, req.body.size());
  5954. EXPECT_EQ("application/octet-stream",
  5955. req.get_header_value("Content-Type"));
  5956. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5957. res.set_content(req.body, "application/octet-stream");
  5958. })
  5959. .Patch("/binary",
  5960. [&](const Request &req, Response &res) {
  5961. EXPECT_EQ(4U, req.body.size());
  5962. EXPECT_EQ("application/octet-stream",
  5963. req.get_header_value("Content-Type"));
  5964. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5965. res.set_content(req.body, "application/octet-stream");
  5966. })
  5967. .Delete("/binary",
  5968. [&](const Request &req, Response &res) {
  5969. EXPECT_EQ(4U, req.body.size());
  5970. EXPECT_EQ("application/octet-stream",
  5971. req.get_header_value("Content-Type"));
  5972. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5973. res.set_content(req.body, "application/octet-stream");
  5974. })
  5975. .Get("/issue1772",
  5976. [&](const Request & /*req*/, Response &res) {
  5977. res.status = 401;
  5978. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5979. })
  5980. .Delete("/issue609",
  5981. [](const httplib::Request &, httplib::Response &res,
  5982. const httplib::ContentReader &) {
  5983. res.set_content("ok", "text/plain");
  5984. })
  5985. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5986. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5987. .Get("/compress",
  5988. [&](const Request & /*req*/, Response &res) {
  5989. res.set_content(
  5990. "12345678901234567890123456789012345678901234567890123456789"
  5991. "01234567890123456789012345678901234567890",
  5992. "text/plain");
  5993. })
  5994. .Get("/compress-with-charset",
  5995. [&](const Request & /*req*/, Response &res) {
  5996. res.set_content(
  5997. "12345678901234567890123456789012345678901234567890123456789"
  5998. "01234567890123456789012345678901234567890",
  5999. "application/json; charset=utf-8");
  6000. })
  6001. .Get("/nocompress",
  6002. [&](const Request & /*req*/, Response &res) {
  6003. res.set_content(
  6004. "12345678901234567890123456789012345678901234567890123456789"
  6005. "01234567890123456789012345678901234567890",
  6006. "application/octet-stream");
  6007. })
  6008. .Post("/compress-multipart",
  6009. [&](const Request &req, Response & /*res*/) {
  6010. EXPECT_EQ(2u, req.form.fields.size());
  6011. ASSERT_TRUE(!req.form.has_field("???"));
  6012. {
  6013. const auto &text = req.form.get_field("key1");
  6014. EXPECT_EQ("test", text);
  6015. }
  6016. {
  6017. const auto &text = req.form.get_field("key2");
  6018. EXPECT_EQ("--abcdefg123", text);
  6019. }
  6020. })
  6021. #endif
  6022. ;
  6023. persons_["john"] = "programmer";
  6024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6025. svr_.wait_until_ready();
  6026. }
  6027. virtual void TearDown() {
  6028. svr_.stop();
  6029. if (!request_threads_.empty()) {
  6030. std::this_thread::sleep_for(std::chrono::seconds(1));
  6031. for (auto &t : request_threads_) {
  6032. t.join();
  6033. }
  6034. }
  6035. t_.join();
  6036. }
  6037. map<string, string> persons_;
  6038. #ifdef CPPHTTPLIB_SSL_ENABLED
  6039. SSLClient cli_;
  6040. SSLServer svr_;
  6041. #else
  6042. Client cli_;
  6043. Server svr_;
  6044. #endif
  6045. thread t_;
  6046. std::vector<thread> request_threads_;
  6047. };
  6048. TEST_F(ServerTest, GetMethod200) {
  6049. auto res = cli_.Get("/hi");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ("HTTP/1.1", res->version);
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. EXPECT_EQ("OK", res->reason);
  6054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6055. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6056. EXPECT_EQ("Hello World!", res->body);
  6057. }
  6058. TEST_F(ServerTest, GetEmptyFile) {
  6059. auto res = cli_.Get("/empty_file");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6063. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6064. EXPECT_EQ("", res->body);
  6065. }
  6066. TEST_F(ServerTest, GetFileContent) {
  6067. auto res = cli_.Get("/file_content");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6071. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6072. EXPECT_EQ("test.html", res->body);
  6073. }
  6074. TEST_F(ServerTest, GetFileContentWithRange) {
  6075. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6078. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6079. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6080. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6081. EXPECT_EQ("est", res->body);
  6082. }
  6083. TEST_F(ServerTest, GetFileContentWithContentType) {
  6084. auto res = cli_.Get("/file_content_with_content_type");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6089. EXPECT_EQ("file\n", res->body);
  6090. }
  6091. TEST_F(ServerTest, GetInvalidFileContent) {
  6092. auto res = cli_.Get("/invalid_file_content");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6095. }
  6096. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6097. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ("HTTP/1.1", res->version);
  6100. EXPECT_EQ(StatusCode::OK_200, res->status);
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6103. EXPECT_EQ("Hello World!", res->body);
  6104. }
  6105. TEST_F(ServerTest, GetMethod302) {
  6106. auto res = cli_.Get("/");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::Found_302, res->status);
  6109. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6110. }
  6111. TEST_F(ServerTest, GetMethod302Redirect) {
  6112. cli_.set_follow_location(true);
  6113. auto res = cli_.Get("/");
  6114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6115. EXPECT_EQ(StatusCode::OK_200, res->status);
  6116. EXPECT_EQ("Hello World!", res->body);
  6117. EXPECT_EQ("/hi", res->location);
  6118. }
  6119. TEST_F(ServerTest, GetMethod404) {
  6120. auto res = cli_.Get("/invalid");
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6123. }
  6124. TEST_F(ServerTest, HeadMethod200) {
  6125. auto res = cli_.Head("/hi");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::OK_200, res->status);
  6128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. EXPECT_TRUE(res->body.empty());
  6130. }
  6131. TEST_F(ServerTest, HeadMethod200Static) {
  6132. auto res = cli_.Head("/mount/dir/index.html");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6136. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6137. EXPECT_TRUE(res->body.empty());
  6138. }
  6139. TEST_F(ServerTest, HeadMethod404) {
  6140. auto res = cli_.Head("/invalid");
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6143. EXPECT_TRUE(res->body.empty());
  6144. }
  6145. TEST_F(ServerTest, GetMethodPersonJohn) {
  6146. auto res = cli_.Get("/person/john");
  6147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6148. EXPECT_EQ(StatusCode::OK_200, res->status);
  6149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("programmer", res->body);
  6151. }
  6152. TEST_F(ServerTest, PostMethod1) {
  6153. auto res = cli_.Get("/person/john1");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6156. res = cli_.Post("/person", "name=john1&note=coder",
  6157. "application/x-www-form-urlencoded");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. res = cli_.Get("/person/john1");
  6161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6162. ASSERT_EQ(StatusCode::OK_200, res->status);
  6163. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6164. ASSERT_EQ("coder", res->body);
  6165. }
  6166. TEST_F(ServerTest, PostMethod2) {
  6167. auto res = cli_.Get("/person/john2");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6170. Params params;
  6171. params.emplace("name", "john2");
  6172. params.emplace("note", "coder");
  6173. res = cli_.Post("/person", params);
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. res = cli_.Get("/person/john2");
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. ASSERT_EQ(StatusCode::OK_200, res->status);
  6179. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6180. ASSERT_EQ("coder", res->body);
  6181. }
  6182. TEST_F(ServerTest, PutMethod3) {
  6183. auto res = cli_.Get("/person/john3");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6186. Params params;
  6187. params.emplace("name", "john3");
  6188. params.emplace("note", "coder");
  6189. res = cli_.Put("/person", params);
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. ASSERT_EQ(StatusCode::OK_200, res->status);
  6192. res = cli_.Get("/person/john3");
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6196. ASSERT_EQ("coder", res->body);
  6197. }
  6198. TEST_F(ServerTest, DeleteMethod1) {
  6199. auto res = cli_.Get("/person/john4");
  6200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6201. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6202. Params params;
  6203. params.emplace("name", "john4");
  6204. params.emplace("note", "coder");
  6205. res = cli_.Post("/person", params);
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. res = cli_.Get("/person/john4");
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. ASSERT_EQ(StatusCode::OK_200, res->status);
  6211. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6212. ASSERT_EQ("coder", res->body);
  6213. Params delete_params;
  6214. delete_params.emplace("name", "john4");
  6215. res = cli_.Delete("/person", delete_params);
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. ASSERT_EQ(StatusCode::OK_200, res->status);
  6218. ASSERT_EQ("DELETED", res->body);
  6219. res = cli_.Get("/person/john4");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6222. }
  6223. TEST_F(ServerTest, DeleteMethod2) {
  6224. auto res = cli_.Get("/person/john5");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6227. Params params;
  6228. params.emplace("name", "john5");
  6229. params.emplace("note", "developer");
  6230. res = cli_.Post("/person", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. res = cli_.Get("/person/john5");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. ASSERT_EQ(StatusCode::OK_200, res->status);
  6236. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6237. ASSERT_EQ("developer", res->body);
  6238. Params delete_params;
  6239. delete_params.emplace("name", "john5");
  6240. Headers headers;
  6241. headers.emplace("Custom-Header", "test-value");
  6242. res = cli_.Delete("/person", headers, delete_params);
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("DELETED", res->body);
  6246. res = cli_.Get("/person/john5");
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6249. }
  6250. TEST_F(ServerTest, DeleteMethod3) {
  6251. auto res = cli_.Get("/person/john6");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6254. Params params;
  6255. params.emplace("name", "john6");
  6256. params.emplace("note", "tester");
  6257. res = cli_.Post("/person", params);
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. ASSERT_EQ(StatusCode::OK_200, res->status);
  6260. res = cli_.Get("/person/john6");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6264. ASSERT_EQ("tester", res->body);
  6265. Params delete_params;
  6266. delete_params.emplace("name", "john6");
  6267. Headers headers;
  6268. headers.emplace("Custom-Header", "test-value");
  6269. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. ASSERT_EQ(StatusCode::OK_200, res->status);
  6272. ASSERT_EQ("DELETED", res->body);
  6273. res = cli_.Get("/person/john6");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6276. }
  6277. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6278. Params params;
  6279. params.emplace("json", JSON_DATA);
  6280. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. ASSERT_EQ(StatusCode::OK_200, res->status);
  6283. ASSERT_EQ(JSON_DATA, res->body);
  6284. }
  6285. TEST_F(ServerTest, PostEmptyContent) {
  6286. auto res = cli_.Post("/empty", "", "text/plain");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. ASSERT_EQ(StatusCode::OK_200, res->status);
  6289. ASSERT_EQ("empty", res->body);
  6290. }
  6291. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6292. auto res = cli_.Post("/empty-no-content-type");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. ASSERT_EQ(StatusCode::OK_200, res->status);
  6295. ASSERT_EQ("empty-no-content-type", res->body);
  6296. }
  6297. TEST_F(ServerTest, PostPathOnly) {
  6298. auto res = cli_.Post("/path-only");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. ASSERT_EQ(StatusCode::OK_200, res->status);
  6301. ASSERT_EQ("path-only", res->body);
  6302. }
  6303. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6304. auto res = cli_.Post("/path-headers-only",
  6305. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. ASSERT_EQ(StatusCode::OK_200, res->status);
  6308. ASSERT_EQ("path-headers-only", res->body);
  6309. }
  6310. TEST_F(ServerTest, PostLarge) {
  6311. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. ASSERT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ(LARGE_DATA, res->body);
  6315. }
  6316. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6317. auto res = cli_.Put("/empty-no-content-type");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. ASSERT_EQ(StatusCode::OK_200, res->status);
  6320. ASSERT_EQ("empty-no-content-type", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDir) {
  6323. auto res = cli_.Get("/dir/");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::OK_200, res->status);
  6326. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6327. auto body = R"(<html>
  6328. <head>
  6329. </head>
  6330. <body>
  6331. <a href="/dir/test.html">Test</a>
  6332. <a href="/hi">hi</a>
  6333. </body>
  6334. </html>
  6335. )";
  6336. EXPECT_EQ(body, res->body);
  6337. }
  6338. TEST_F(ServerTest, GetMethodDirTest) {
  6339. auto res = cli_.Get("/dir/test.html");
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. EXPECT_EQ(StatusCode::OK_200, res->status);
  6342. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6343. EXPECT_EQ("test.html", res->body);
  6344. }
  6345. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6346. auto res = cli_.Get("/dir/../dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodInvalidPath) {
  6351. auto res = cli_.Get("/dir/../test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6356. auto res = cli_.Get("/../www/dir/test.html");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6359. }
  6360. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6361. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST_F(ServerTest, GetMethodDirMountTest) {
  6366. auto res = cli_.Get("/mount/dir/test.html");
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6370. EXPECT_EQ("test.html", res->body);
  6371. }
  6372. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6373. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6376. }
  6377. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6378. auto res = cli_.Get("/mount/dir/../test.html");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6381. }
  6382. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6383. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6386. }
  6387. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6388. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6391. }
  6392. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6393. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6396. }
  6397. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6398. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6401. }
  6402. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6403. auto res = cli_.Get("/mount/dir");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6406. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6407. }
  6408. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6409. auto res = cli_.Get("//dir");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6412. EXPECT_FALSE(res->has_header("Location"));
  6413. }
  6414. TEST_F(ServerTest, PostMethod303) {
  6415. auto res = cli_.Post("/1", "body", "text/plain");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6418. EXPECT_EQ("/2", res->get_header_value("Location"));
  6419. }
  6420. TEST_F(ServerTest, PostMethod303Redirect) {
  6421. cli_.set_follow_location(true);
  6422. auto res = cli_.Post("/1", "body", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::OK_200, res->status);
  6425. EXPECT_EQ("redirected.", res->body);
  6426. EXPECT_EQ("/2", res->location);
  6427. }
  6428. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6429. auto res = cli_.Get("/dir/test.abcde");
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::OK_200, res->status);
  6432. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6433. EXPECT_EQ("abcde", res->body);
  6434. }
  6435. TEST_F(ServerTest, StaticFileRange) {
  6436. auto res =
  6437. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6440. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6444. EXPECT_EQ(std::string("cd"), res->body);
  6445. }
  6446. TEST_F(ServerTest, StaticFileRanges) {
  6447. auto res = cli_.Get("/dir/test.abcde",
  6448. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6451. EXPECT_TRUE(
  6452. res->get_header_value("Content-Type")
  6453. .find(
  6454. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6455. 0);
  6456. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6457. }
  6458. TEST_F(ServerTest, StaticFileRangeHead) {
  6459. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6462. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6463. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6464. EXPECT_EQ(true, res->has_header("Content-Range"));
  6465. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6466. }
  6467. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6468. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6472. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6473. EXPECT_EQ(true, res->has_header("Content-Range"));
  6474. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6475. res->get_header_value("Content-Range"));
  6476. EXPECT_EQ("LAST\n", res->body);
  6477. }
  6478. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6479. auto res =
  6480. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6484. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6485. EXPECT_EQ(true, res->has_header("Content-Range"));
  6486. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6487. }
  6488. TEST_F(ServerTest, StaticFileBigFile) {
  6489. auto res = cli_.Get("/dir/1MB.txt");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6494. }
  6495. TEST_F(ServerTest, InvalidBaseDirMount) {
  6496. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6497. }
  6498. TEST_F(ServerTest, Binary) {
  6499. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6500. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6501. "application/octet-stream");
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. ASSERT_EQ(StatusCode::OK_200, res->status);
  6504. ASSERT_EQ(4U, res->body.size());
  6505. res = cli_.Put("/binary", binary.data(), binary.size(),
  6506. "application/octet-stream");
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. ASSERT_EQ(StatusCode::OK_200, res->status);
  6509. ASSERT_EQ(4U, res->body.size());
  6510. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6511. "application/octet-stream");
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. ASSERT_EQ(StatusCode::OK_200, res->status);
  6514. ASSERT_EQ(4U, res->body.size());
  6515. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6516. "application/octet-stream");
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. ASSERT_EQ(StatusCode::OK_200, res->status);
  6519. ASSERT_EQ(4U, res->body.size());
  6520. }
  6521. TEST_F(ServerTest, BinaryString) {
  6522. auto binary = std::string("\x00\x01\x02\x03", 4);
  6523. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. ASSERT_EQ(StatusCode::OK_200, res->status);
  6526. ASSERT_EQ(4U, res->body.size());
  6527. res = cli_.Put("/binary", binary, "application/octet-stream");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. ASSERT_EQ(StatusCode::OK_200, res->status);
  6530. ASSERT_EQ(4U, res->body.size());
  6531. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6533. ASSERT_EQ(StatusCode::OK_200, res->status);
  6534. ASSERT_EQ(4U, res->body.size());
  6535. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. ASSERT_EQ(StatusCode::OK_200, res->status);
  6538. ASSERT_EQ(4U, res->body.size());
  6539. }
  6540. TEST_F(ServerTest, EmptyRequest) {
  6541. auto res = cli_.Get("");
  6542. ASSERT_TRUE(!res);
  6543. EXPECT_EQ(Error::Connection, res.error());
  6544. }
  6545. TEST_F(ServerTest, LongRequest) {
  6546. std::string request;
  6547. for (size_t i = 0; i < 545; i++) {
  6548. request += "/TooLongRequest";
  6549. }
  6550. request += "OK";
  6551. auto res = cli_.Get(request.c_str());
  6552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6554. }
  6555. TEST_F(ServerTest, TooLongRequest) {
  6556. std::string request;
  6557. for (size_t i = 0; i < 546; i++) {
  6558. request += "/TooLongRequest";
  6559. }
  6560. request += "_NG";
  6561. auto start = std::chrono::high_resolution_clock::now();
  6562. cli_.set_keep_alive(true);
  6563. auto res = cli_.Get(request.c_str());
  6564. auto end = std::chrono::high_resolution_clock::now();
  6565. auto elapsed =
  6566. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6567. .count();
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6570. EXPECT_LE(elapsed, 1000);
  6571. EXPECT_EQ("close", res->get_header_value("Connection"));
  6572. EXPECT_FALSE(cli_.is_socket_open());
  6573. }
  6574. TEST_F(ServerTest, AlmostTooLongRequest) {
  6575. // test for #2046 - URI length check shouldn't include other content on req
  6576. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6577. // leading /, space, HTTP/1.1)
  6578. std::string request =
  6579. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6580. auto res = cli_.Get(request.c_str());
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6583. }
  6584. TEST_F(ServerTest, LongHeader) {
  6585. Request req;
  6586. req.method = "GET";
  6587. req.path = "/hi";
  6588. std::string host_and_port;
  6589. host_and_port += HOST;
  6590. host_and_port += ":";
  6591. host_and_port += std::to_string(PORT);
  6592. req.headers.emplace("Host", host_and_port.c_str());
  6593. req.headers.emplace("Accept", "*/*");
  6594. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6595. req.headers.emplace(
  6596. "Header-Name",
  6597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@");
  6626. auto res = std::make_shared<Response>();
  6627. auto error = Error::Success;
  6628. auto ret = cli_.send(req, *res, error);
  6629. ASSERT_TRUE(ret);
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. }
  6632. TEST_F(ServerTest, LongQueryValue) {
  6633. auto start = std::chrono::high_resolution_clock::now();
  6634. cli_.set_keep_alive(true);
  6635. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6636. auto end = std::chrono::high_resolution_clock::now();
  6637. auto elapsed =
  6638. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6639. .count();
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6642. EXPECT_LE(elapsed, 1000);
  6643. EXPECT_EQ("close", res->get_header_value("Connection"));
  6644. EXPECT_FALSE(cli_.is_socket_open());
  6645. }
  6646. TEST_F(ServerTest, TooLongQueryValue) {
  6647. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6648. ASSERT_FALSE(res);
  6649. EXPECT_EQ(Error::Read, res.error());
  6650. }
  6651. TEST_F(ServerTest, TooLongHeader) {
  6652. Request req;
  6653. req.method = "GET";
  6654. req.path = "/hi";
  6655. std::string host_and_port;
  6656. host_and_port += HOST;
  6657. host_and_port += ":";
  6658. host_and_port += std::to_string(PORT);
  6659. req.headers.emplace("Host", host_and_port.c_str());
  6660. req.headers.emplace("Accept", "*/*");
  6661. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6662. req.headers.emplace(
  6663. "Header-Name",
  6664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6692. "@@@@@@@@@@@@@@@@@");
  6693. auto res = std::make_shared<Response>();
  6694. auto error = Error::Success;
  6695. auto ret = cli_.send(req, *res, error);
  6696. ASSERT_TRUE(ret);
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. }
  6699. TEST_F(ServerTest, HeaderCountAtLimit) {
  6700. // Test with headers just under the 100 limit
  6701. httplib::Headers headers;
  6702. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6703. // This should keep us just under the 100 header limit
  6704. for (int i = 0; i < 95; i++) {
  6705. std::string name = "X-Test-Header-" + std::to_string(i);
  6706. std::string value = "value" + std::to_string(i);
  6707. headers.emplace(name, value);
  6708. }
  6709. // This should work fine as we're under the limit
  6710. auto res = cli_.Get("/hi", headers);
  6711. EXPECT_TRUE(res);
  6712. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6713. }
  6714. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6715. // Test with many headers to exceed the 100 limit
  6716. httplib::Headers headers;
  6717. // Add 150 headers to definitely exceed the 100 limit
  6718. for (int i = 0; i < 150; i++) {
  6719. std::string name = "X-Test-Header-" + std::to_string(i);
  6720. std::string value = "value" + std::to_string(i);
  6721. headers.emplace(name, value);
  6722. }
  6723. // This should fail due to exceeding header count limit
  6724. cli_.set_keep_alive(true);
  6725. auto res = cli_.Get("/hi", headers);
  6726. // The server should respond with 400 Bad Request
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ("close", res->get_header_value("Connection"));
  6730. EXPECT_FALSE(cli_.is_socket_open());
  6731. }
  6732. TEST_F(ServerTest, PercentEncoding) {
  6733. auto res = cli_.Get("/e%6edwith%");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, PercentEncodingUnicode) {
  6738. auto res = cli_.Get("/e%u006edwith%");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::OK_200, res->status);
  6741. }
  6742. TEST_F(ServerTest, InvalidPercentEncoding) {
  6743. auto res = cli_.Get("/%endwith%");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6746. }
  6747. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6748. auto res = cli_.Get("/%uendwith%");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6751. }
  6752. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6753. auto res = cli_.Get("/hello?aaa=bbb%");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6756. }
  6757. TEST_F(ServerTest, PlusSignEncoding) {
  6758. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ("a +b", res->body);
  6762. }
  6763. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6764. // This test simulates a potential DoS attack using many headers
  6765. // to verify our security fix prevents memory exhaustion
  6766. httplib::Headers attack_headers;
  6767. // Attempt to add many headers like an attacker would (200 headers to far
  6768. // exceed limit)
  6769. for (int i = 0; i < 200; i++) {
  6770. std::string name = "X-Attack-Header-" + std::to_string(i);
  6771. std::string value = "attack_payload_" + std::to_string(i);
  6772. attack_headers.emplace(name, value);
  6773. }
  6774. // Try to POST with excessive headers
  6775. cli_.set_keep_alive(true);
  6776. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6777. // Should either fail or return 400 Bad Request due to security limit
  6778. if (res) {
  6779. // If we get a response, it should be 400 Bad Request
  6780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6781. EXPECT_EQ("close", res->get_header_value("Connection"));
  6782. }
  6783. EXPECT_FALSE(cli_.is_socket_open());
  6784. }
  6785. TEST_F(ServerTest, MultipartFormData) {
  6786. UploadFormDataItems items = {
  6787. {"text1", "text default", "", ""},
  6788. {"text2", "aωb", "", ""},
  6789. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6790. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6791. {"file3", "", "", "application/octet-stream"},
  6792. {"file4", "", "", " application/json tmp-string "}};
  6793. auto res = cli_.Post("/multipart", items);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6798. UploadFormDataItems items = {
  6799. {"text", "default text", "", ""},
  6800. {"multi_text1", "aaaaa", "", ""},
  6801. {"multi_text1", "bbbbb", "", ""},
  6802. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6803. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6804. "application/json"},
  6805. };
  6806. auto res = cli_.Post("/multipart/multi_file_values", items);
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. }
  6810. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6811. auto res = cli_.Get("/hi");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6815. EXPECT_EQ("Hello World!", res->body);
  6816. }
  6817. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6818. Request req;
  6819. req.method = "POST";
  6820. req.path = "/chunked";
  6821. std::string host_and_port;
  6822. host_and_port += HOST;
  6823. host_and_port += ":";
  6824. host_and_port += std::to_string(PORT);
  6825. req.headers.emplace("Host", host_and_port.c_str());
  6826. req.headers.emplace("Accept", "*/*");
  6827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6828. req.headers.emplace("Content-Type", "text/plain");
  6829. req.headers.emplace("Content-Length", "0");
  6830. req.headers.emplace(
  6831. "Transfer-Encoding",
  6832. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6833. // Client does not chunk, so make a chunked body manually.
  6834. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6835. auto res = std::make_shared<Response>();
  6836. auto error = Error::Success;
  6837. auto ret = cli_.send(req, *res, error);
  6838. ASSERT_TRUE(ret);
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. template <typename ClientT>
  6842. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6843. int expected_status) {
  6844. Request req;
  6845. req.method = "POST";
  6846. req.path = "/chunked";
  6847. std::string host_and_port;
  6848. host_and_port += HOST;
  6849. host_and_port += ":";
  6850. host_and_port += std::to_string(PORT);
  6851. req.headers.emplace("Host", host_and_port.c_str());
  6852. req.headers.emplace("Content-Length", "0");
  6853. req.headers.emplace("Transfer-Encoding", "chunked");
  6854. req.body = body;
  6855. auto res = std::make_shared<Response>();
  6856. auto error = Error::Success;
  6857. ASSERT_TRUE(cli.send(req, *res, error));
  6858. EXPECT_EQ(expected_status, res->status);
  6859. }
  6860. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6861. // rather than treat them as valid lengths.
  6862. template <typename ClientT>
  6863. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6864. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6865. }
  6866. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6867. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6868. }
  6869. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6870. expect_chunked_body_rejected(
  6871. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6872. }
  6873. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6874. // chunk-size line carries no CR, LF or other control character ahead of its
  6875. // terminator. Such a line must be refused rather than read as extension text.
  6876. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6877. expect_chunked_body_rejected(
  6878. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6879. }
  6880. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6881. expect_chunked_body_rejected(
  6882. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6883. }
  6884. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6885. expect_chunked_body_rejected(
  6886. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6887. }
  6888. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6889. // The literal stays split: a hex escape consumes every hex digit that
  6890. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6891. expect_chunked_body_rejected(
  6892. cli_, "4;a\x01"
  6893. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6894. }
  6895. // The bytes around chunk data are no payload, so they cannot ride on the
  6896. // payload limit
  6897. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6898. // Small enough that the whole request is sent before the server turns it
  6899. // down, yet past the limit by the last chunks
  6900. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6901. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6902. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6903. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6904. SCOPED_TRACE(size_line.substr(0, 2));
  6905. std::string body;
  6906. for (auto c : std::string("dechunked post body")) {
  6907. body += size_line + "\r\n" + c + "\r\n";
  6908. }
  6909. body += "0\r\n\r\n";
  6910. expect_chunked_body_rejected(cli_, body.c_str());
  6911. }
  6912. }
  6913. TEST_F(ServerTest, AcceptsChunkExtension) {
  6914. expect_chunked_body_status(cli_,
  6915. "4;name=value\r\ndech\r\n"
  6916. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6917. "0;last\r\n\r\n",
  6918. StatusCode::OK_200);
  6919. }
  6920. TEST_F(ServerTest, GetStreamed2) {
  6921. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6924. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6925. EXPECT_EQ(true, res->has_header("Content-Range"));
  6926. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6927. EXPECT_EQ(std::string("ab"), res->body);
  6928. }
  6929. TEST_F(ServerTest, GetStreamed) {
  6930. auto res = cli_.Get("/streamed");
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6934. EXPECT_EQ(std::string("aaabbb"), res->body);
  6935. }
  6936. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6937. auto res = cli_.Get("/streamed-without-length",
  6938. Headers{make_range_header({{0, -1}})});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ(false, res->has_header("Content-Length"));
  6942. EXPECT_EQ(false, res->has_header("Content-Range"));
  6943. EXPECT_EQ(std::string("abcdefg"), res->body);
  6944. }
  6945. TEST_F(ServerTest, GetStreamedWithRange1) {
  6946. auto res =
  6947. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6950. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6951. EXPECT_EQ(true, res->has_header("Content-Range"));
  6952. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6953. EXPECT_EQ(std::string("def"), res->body);
  6954. }
  6955. TEST_F(ServerTest, GetStreamedWithRange2) {
  6956. auto res =
  6957. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6960. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6961. EXPECT_EQ(true, res->has_header("Content-Range"));
  6962. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6963. EXPECT_EQ(std::string("bcdefg"), res->body);
  6964. }
  6965. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6966. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6969. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(true, res->has_header("Content-Range"));
  6971. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6972. EXPECT_EQ(std::string("efg"), res->body);
  6973. }
  6974. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6975. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6976. // the entire representation.
  6977. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6978. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6982. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6983. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6984. }
  6985. }
  6986. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6987. auto res =
  6988. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6991. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6992. EXPECT_EQ(false, res->has_header("Content-Range"));
  6993. EXPECT_EQ(0U, res->body.size());
  6994. }
  6995. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6996. // Only a 206 is served as a partial representation. Under any other status
  6997. // `apply_ranges()` reported the full content length, so the body must match
  6998. // that header, and the content provider must never be asked for an offset
  6999. // outside the representation.
  7000. auto check = [&](int status, const char *range) {
  7001. auto path =
  7002. std::string("/streamed-with-range?status=") + std::to_string(status);
  7003. auto ctx = path + " Range: " + range;
  7004. auto res = cli_.Get(path, Headers{{"Range", range}});
  7005. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7006. EXPECT_EQ(status, res->status) << ctx;
  7007. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7009. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7010. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7011. };
  7012. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7013. check(403, "bytes=3-5");
  7014. // The offset is far past the representation.
  7015. check(403, "bytes=100000-100200");
  7016. // `first_pos` is still -1 here, and the bounds asserts in
  7017. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7018. check(403, "bytes=-3");
  7019. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7020. // multipart branch would have written one that is empty.
  7021. check(403, "bytes=1-2, 4-5");
  7022. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7023. // covers the whole representation.
  7024. check(200, "bytes=3-5");
  7025. check(200, "bytes=1-2, 4-5");
  7026. }
  7027. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7028. auto res =
  7029. cli_.Get("/streamed-with-range",
  7030. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7031. "92233720368547758079223372036854775807"}});
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7034. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7035. EXPECT_EQ(false, res->has_header("Content-Range"));
  7036. EXPECT_EQ(0U, res->body.size());
  7037. }
  7038. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7039. auto res = cli_.Get(
  7040. "/with-range",
  7041. Headers{{"Range",
  7042. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7043. {"Accept-Encoding", ""}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7047. EXPECT_EQ(true, res->has_header("Content-Range"));
  7048. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7049. EXPECT_EQ(std::string("abcdefg"), res->body);
  7050. }
  7051. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7052. auto res = cli_.Get("/with-range", Headers{
  7053. {"Range", "bytes=0-"},
  7054. {"Accept-Encoding", ""},
  7055. });
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7059. EXPECT_EQ(true, res->has_header("Content-Range"));
  7060. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7061. EXPECT_EQ(std::string("abcdefg"), res->body);
  7062. }
  7063. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7064. auto res = cli_.Get("/streamed-with-range",
  7065. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7068. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7069. EXPECT_EQ(false, res->has_header("Content-Range"));
  7070. EXPECT_EQ(267U, res->body.size());
  7071. // Check that both range contents are present
  7072. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7073. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7074. // Check that Content-Range headers are present for both ranges
  7075. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7076. std::string::npos);
  7077. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7078. std::string::npos);
  7079. }
  7080. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7081. Ranges ranges;
  7082. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7083. ranges.emplace_back(0, -1);
  7084. }
  7085. auto res = cli_.Get("/streamed-with-range?error",
  7086. Headers{{make_range_header(ranges)}});
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7089. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7090. EXPECT_EQ(false, res->has_header("Content-Range"));
  7091. EXPECT_EQ(0U, res->body.size());
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7094. auto res = cli_.Get("/streamed-with-range",
  7095. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ(5U, res->body.size());
  7099. // Check that overlapping ranges are coalesced into a single range
  7100. EXPECT_EQ("bcdef", res->body);
  7101. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7102. // Should be single range, not multipart
  7103. EXPECT_TRUE(res->has_header("Content-Range"));
  7104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7105. }
  7106. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7107. auto res = cli_.Get("/streamed-with-range",
  7108. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7111. EXPECT_EQ(268U, res->body.size());
  7112. // Check that both range contents are present
  7113. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7114. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7115. // Check that Content-Range headers are present for both ranges
  7116. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7117. std::string::npos);
  7118. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7119. std::string::npos);
  7120. }
  7121. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7122. auto res = cli_.Get("/streamed-with-range",
  7123. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ(269U, res->body.size());
  7127. // Check that both duplicate range contents are present
  7128. size_t first_abc = res->body.find("abc\r\n");
  7129. EXPECT_TRUE(first_abc != std::string::npos);
  7130. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7131. EXPECT_TRUE(second_abc != std::string::npos);
  7132. // Check that Content-Range headers are present for both ranges
  7133. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7134. EXPECT_TRUE(first_range != std::string::npos);
  7135. size_t second_range =
  7136. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7137. EXPECT_TRUE(second_range != std::string::npos);
  7138. }
  7139. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7140. auto res =
  7141. cli_.Get("/streamed-with-range?error",
  7142. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7145. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7146. EXPECT_EQ(false, res->has_header("Content-Range"));
  7147. EXPECT_EQ(0U, res->body.size());
  7148. }
  7149. TEST_F(ServerTest, GetStreamedEndless) {
  7150. uint64_t offset = 0;
  7151. auto res = cli_.Get("/streamed-cancel",
  7152. [&](const char * /*data*/, uint64_t data_length) {
  7153. if (offset < 100) {
  7154. offset += data_length;
  7155. return true;
  7156. }
  7157. return false;
  7158. });
  7159. ASSERT_TRUE(!res);
  7160. EXPECT_EQ(Error::Canceled, res.error());
  7161. }
  7162. TEST_F(ServerTest, ClientStop) {
  7163. std::atomic_size_t count{4};
  7164. std::vector<std::thread> threads;
  7165. for (auto i = count.load(); i != 0; --i) {
  7166. threads.emplace_back([&]() {
  7167. auto res = cli_.Get("/streamed-cancel",
  7168. [&](const char *, uint64_t) { return true; });
  7169. --count;
  7170. ASSERT_TRUE(!res);
  7171. EXPECT_TRUE(res.error() == Error::Canceled ||
  7172. res.error() == Error::Read || res.error() == Error::Write);
  7173. });
  7174. }
  7175. std::this_thread::sleep_for(std::chrono::seconds(2));
  7176. while (count != 0) {
  7177. cli_.stop();
  7178. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7179. }
  7180. for (auto &t : threads) {
  7181. t.join();
  7182. }
  7183. }
  7184. TEST_F(ServerTest, GetWithRange1) {
  7185. auto res = cli_.Get("/with-range", Headers{
  7186. make_range_header({{3, 5}}),
  7187. {"Accept-Encoding", ""},
  7188. });
  7189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7191. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7192. EXPECT_EQ(true, res->has_header("Content-Range"));
  7193. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7194. EXPECT_EQ(std::string("def"), res->body);
  7195. }
  7196. TEST_F(ServerTest, GetWithRange2) {
  7197. auto res = cli_.Get("/with-range", Headers{
  7198. make_range_header({{1, -1}}),
  7199. {"Accept-Encoding", ""},
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(true, res->has_header("Content-Range"));
  7205. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7206. EXPECT_EQ(std::string("bcdefg"), res->body);
  7207. }
  7208. TEST_F(ServerTest, GetWithRange3) {
  7209. auto res = cli_.Get("/with-range", Headers{
  7210. make_range_header({{0, 0}}),
  7211. {"Accept-Encoding", ""},
  7212. });
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7215. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7216. EXPECT_EQ(true, res->has_header("Content-Range"));
  7217. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7218. EXPECT_EQ(std::string("a"), res->body);
  7219. }
  7220. TEST_F(ServerTest, GetWithRange4) {
  7221. auto res = cli_.Get("/with-range", Headers{
  7222. make_range_header({{-1, 2}}),
  7223. {"Accept-Encoding", ""},
  7224. });
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7228. EXPECT_EQ(true, res->has_header("Content-Range"));
  7229. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7230. EXPECT_EQ(std::string("fg"), res->body);
  7231. }
  7232. TEST_F(ServerTest, GetWithRange5) {
  7233. auto res = cli_.Get("/with-range", Headers{
  7234. make_range_header({{0, 5}}),
  7235. {"Accept-Encoding", ""},
  7236. });
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7239. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7240. EXPECT_EQ(true, res->has_header("Content-Range"));
  7241. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7242. EXPECT_EQ(std::string("abcdef"), res->body);
  7243. }
  7244. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7245. auto res =
  7246. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7249. }
  7250. TEST_F(ServerTest, GetWithRangeMultipart) {
  7251. auto res =
  7252. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7256. EXPECT_EQ(false, res->has_header("Content-Range"));
  7257. EXPECT_EQ(267U, res->body.size());
  7258. }
  7259. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7260. auto res = cli_.Get("/with-range",
  7261. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7264. }
  7265. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7266. auto res = cli_.Get("/with-range-customized-response",
  7267. Headers{{make_range_header({{1, 2}})}});
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7270. EXPECT_EQ(true, res->has_header("Content-Length"));
  7271. EXPECT_EQ(false, res->has_header("Content-Range"));
  7272. EXPECT_EQ(JSON_DATA, res->body);
  7273. }
  7274. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7275. auto res = cli_.Get("/with-range-customized-response",
  7276. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7279. EXPECT_EQ(true, res->has_header("Content-Length"));
  7280. EXPECT_EQ(false, res->has_header("Content-Range"));
  7281. EXPECT_EQ(JSON_DATA, res->body);
  7282. }
  7283. TEST_F(ServerTest, Issue1772) {
  7284. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7287. }
  7288. TEST_F(ServerTest, Issue609) {
  7289. auto res = cli_.Delete("/issue609");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. EXPECT_EQ(std::string("ok"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetStreamedChunked) {
  7295. auto res = cli_.Get("/streamed-chunked");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ(std::string("123456789"), res->body);
  7299. }
  7300. TEST_F(ServerTest, GetStreamedChunked2) {
  7301. auto res = cli_.Get("/streamed-chunked2");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ(std::string("123456789"), res->body);
  7305. }
  7306. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7307. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ(std::string("123456789"), res->body);
  7311. EXPECT_TRUE(res->has_header("Trailer"));
  7312. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7313. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7314. // Trailers are now stored separately from headers (security fix)
  7315. EXPECT_EQ(2U, res->trailers.size());
  7316. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7317. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7318. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7319. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7320. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7321. // Verify trailers are NOT in headers (security verification)
  7322. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7323. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7324. }
  7325. TEST_F(ServerTest, LargeChunkedPost) {
  7326. Request req;
  7327. req.method = "POST";
  7328. req.path = "/large-chunked";
  7329. std::string host_and_port;
  7330. host_and_port += HOST;
  7331. host_and_port += ":";
  7332. host_and_port += std::to_string(PORT);
  7333. req.headers.emplace("Host", host_and_port.c_str());
  7334. req.headers.emplace("Accept", "*/*");
  7335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7336. req.headers.emplace("Content-Type", "text/plain");
  7337. req.headers.emplace("Content-Length", "0");
  7338. req.headers.emplace("Transfer-Encoding", "chunked");
  7339. std::string long_string(30 * 1024u, 'a');
  7340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7341. // Attempt to make a large enough post to exceed OS buffers, to test that
  7342. // the server handles short reads if the full chunk data isn't available.
  7343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7344. auto res = std::make_shared<Response>();
  7345. auto error = Error::Success;
  7346. auto ret = cli_.send(req, *res, error);
  7347. ASSERT_TRUE(ret);
  7348. EXPECT_EQ(StatusCode::OK_200, res->status);
  7349. }
  7350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7351. auto res = cli_.Get("/remote_addr");
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::OK_200, res->status);
  7354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7356. }
  7357. TEST_F(ServerTest, GetMethodLocalAddr) {
  7358. auto res = cli_.Get("/local_addr");
  7359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7362. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7363. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7364. }
  7365. TEST_F(ServerTest, HTTPResponseSplitting) {
  7366. auto res = cli_.Get("/http_response_splitting");
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. }
  7370. TEST_F(ServerTest, SlowRequest) {
  7371. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7372. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7373. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7374. }
  7375. #if 0
  7376. TEST_F(ServerTest, SlowPost) {
  7377. char buffer[64 * 1024];
  7378. memset(buffer, 0x42, sizeof(buffer));
  7379. auto res = cli_.Post(
  7380. "/slowpost", 64 * 1024 * 1024,
  7381. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7382. auto ret = sink.write(buffer, sizeof(buffer));
  7383. EXPECT_TRUE(ret);
  7384. return true;
  7385. },
  7386. "text/plain");
  7387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7388. EXPECT_EQ(StatusCode::OK_200, res->status);
  7389. }
  7390. TEST_F(ServerTest, SlowPostFail) {
  7391. char buffer[64 * 1024];
  7392. memset(buffer, 0x42, sizeof(buffer));
  7393. cli_.set_write_timeout(std::chrono::seconds(0));
  7394. auto res = cli_.Post(
  7395. "/slowpost", 64 * 1024 * 1024,
  7396. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7397. sink.write(buffer, sizeof(buffer));
  7398. return true;
  7399. },
  7400. "text/plain");
  7401. ASSERT_TRUE(!res);
  7402. EXPECT_EQ(Error::Write, res.error());
  7403. }
  7404. #endif
  7405. TEST_F(ServerTest, Put) {
  7406. auto res = cli_.Put("/put", "PUT", "text/plain");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ("PUT", res->body);
  7410. }
  7411. TEST_F(ServerTest, PutWithContentProvider) {
  7412. auto res = cli_.Put(
  7413. "/put", 3,
  7414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7415. sink.os << "PUT";
  7416. return true;
  7417. },
  7418. "text/plain");
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ("PUT", res->body);
  7422. }
  7423. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7424. auto res = cli_.Post(
  7425. "/post", 42,
  7426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7427. return false;
  7428. },
  7429. "text/plain");
  7430. ASSERT_TRUE(!res);
  7431. EXPECT_EQ(Error::Canceled, res.error());
  7432. }
  7433. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7434. auto res = cli_.Put(
  7435. "/put",
  7436. [](size_t /*offset*/, DataSink &sink) {
  7437. sink.os << "PUT";
  7438. sink.done();
  7439. return true;
  7440. },
  7441. "text/plain");
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::OK_200, res->status);
  7444. EXPECT_EQ("PUT", res->body);
  7445. }
  7446. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7447. auto res = cli_.Post(
  7448. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7449. "text/plain");
  7450. ASSERT_TRUE(!res);
  7451. EXPECT_EQ(Error::Canceled, res.error());
  7452. }
  7453. TEST_F(ServerTest, PostLoopBack) {
  7454. std::string body;
  7455. auto res = cli_.Post(
  7456. "/post-loopback", 9,
  7457. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7458. EXPECT_EQ(9u, length);
  7459. sink.write("123", 3);
  7460. sink.write("456", 3);
  7461. sink.write("789", 3);
  7462. return true;
  7463. },
  7464. "text/plain",
  7465. [&body](const char *data, size_t data_length) {
  7466. body.append(data, data_length);
  7467. return true;
  7468. });
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. EXPECT_EQ("123456789", body);
  7472. }
  7473. TEST_F(ServerTest, PutLoopBack) {
  7474. std::string body;
  7475. auto res = cli_.Put(
  7476. "/put-loopback", 9,
  7477. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7478. EXPECT_EQ(9u, length);
  7479. sink.write("123", 3);
  7480. sink.write("456", 3);
  7481. sink.write("789", 3);
  7482. return true;
  7483. },
  7484. "text/plain",
  7485. [&body](const char *data, size_t data_length) {
  7486. body.append(data, data_length);
  7487. return true;
  7488. });
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ("123456789", body);
  7492. }
  7493. TEST_F(ServerTest, PatchLoopBack) {
  7494. std::string body;
  7495. auto res = cli_.Patch(
  7496. "/patch-loopback", 9,
  7497. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7498. EXPECT_EQ(9u, length);
  7499. sink.write("123", 3);
  7500. sink.write("456", 3);
  7501. sink.write("789", 3);
  7502. return true;
  7503. },
  7504. "text/plain",
  7505. [&body](const char *data, size_t data_length) {
  7506. body.append(data, data_length);
  7507. return true;
  7508. });
  7509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7510. EXPECT_EQ(StatusCode::OK_200, res->status);
  7511. EXPECT_EQ("123456789", body);
  7512. }
  7513. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7514. std::string body;
  7515. auto res = cli_.Post(
  7516. "/post-loopback",
  7517. [](size_t /*offset*/, DataSink &sink) {
  7518. sink.write("123", 3);
  7519. sink.write("456", 3);
  7520. sink.write("789", 3);
  7521. sink.done();
  7522. return true;
  7523. },
  7524. "text/plain",
  7525. [&body](const char *data, size_t data_length) {
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. EXPECT_EQ("123456789", body);
  7532. }
  7533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7534. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7535. cli_.set_compress(true);
  7536. auto res = cli_.Put(
  7537. "/put", 3,
  7538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7539. sink.os << "PUT";
  7540. return true;
  7541. },
  7542. "text/plain");
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. EXPECT_EQ("PUT", res->body);
  7546. }
  7547. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7548. cli_.set_compress(true);
  7549. auto res = cli_.Post(
  7550. "/post", 42,
  7551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7552. return false;
  7553. },
  7554. "text/plain");
  7555. ASSERT_TRUE(!res);
  7556. EXPECT_EQ(Error::Canceled, res.error());
  7557. }
  7558. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7559. cli_.set_compress(true);
  7560. auto res = cli_.Put(
  7561. "/put",
  7562. [](size_t /*offset*/, DataSink &sink) {
  7563. sink.os << "PUT";
  7564. sink.done();
  7565. return true;
  7566. },
  7567. "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, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7573. cli_.set_compress(true);
  7574. auto res = cli_.Post(
  7575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7576. "text/plain");
  7577. ASSERT_TRUE(!res);
  7578. EXPECT_EQ(Error::Canceled, res.error());
  7579. }
  7580. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7581. cli_.set_compress(true);
  7582. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. EXPECT_EQ(LARGE_DATA, res->body);
  7586. }
  7587. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7588. #ifdef CPPHTTPLIB_SSL_ENABLED
  7589. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7590. Client cli(s.c_str());
  7591. cli.enable_server_certificate_verification(false);
  7592. #else
  7593. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7594. Client cli(s.c_str());
  7595. #endif
  7596. cli.set_compress(true);
  7597. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ(LARGE_DATA, res->body);
  7601. // The compressed size should be less than a 10th of the original. May vary
  7602. // depending on the zlib library.
  7603. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7604. static_cast<uint64_t>(10 * 1024 * 1024));
  7605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7606. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7607. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7608. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7609. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7610. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7611. #endif
  7612. }
  7613. TEST_F(ServerTest, PutContentWithDeflate) {
  7614. cli_.set_compress(false);
  7615. Headers headers;
  7616. headers.emplace("Content-Encoding", "deflate");
  7617. // PUT in deflate format:
  7618. auto res = cli_.Put("/put", headers,
  7619. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7621. EXPECT_EQ(StatusCode::OK_200, res->status);
  7622. EXPECT_EQ("PUT", res->body);
  7623. }
  7624. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7625. Headers headers;
  7626. headers.emplace("Accept-Encoding", "gzip, deflate");
  7627. auto res = cli_.Get("/streamed-chunked", headers);
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::OK_200, res->status);
  7630. EXPECT_EQ(std::string("123456789"), res->body);
  7631. }
  7632. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7633. Headers headers;
  7634. headers.emplace("Accept-Encoding", "gzip, deflate");
  7635. auto res = cli_.Get("/streamed-chunked2", headers);
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. EXPECT_EQ(std::string("123456789"), res->body);
  7639. }
  7640. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7641. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. }
  7645. TEST(GzipDecompressor, ChunkedDecompression) {
  7646. std::string data;
  7647. for (size_t i = 0; i < 32 * 1024; ++i) {
  7648. data.push_back(static_cast<char>('a' + i % 26));
  7649. }
  7650. std::string compressed_data;
  7651. {
  7652. httplib::detail::gzip_compressor compressor;
  7653. bool result = compressor.compress(
  7654. data.data(), data.size(),
  7655. /*last=*/true,
  7656. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7657. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7658. compressed_data_size);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(result);
  7662. }
  7663. std::string decompressed_data;
  7664. {
  7665. httplib::detail::gzip_decompressor decompressor;
  7666. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7667. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7668. size_t chunk_size = 130;
  7669. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7670. chunk_begin += chunk_size) {
  7671. size_t current_chunk_size =
  7672. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7673. bool result = decompressor.decompress(
  7674. compressed_data.data() + chunk_begin, current_chunk_size,
  7675. [&](const char *decompressed_data_chunk,
  7676. size_t decompressed_data_chunk_size) {
  7677. decompressed_data.insert(decompressed_data.size(),
  7678. decompressed_data_chunk,
  7679. decompressed_data_chunk_size);
  7680. return true;
  7681. });
  7682. ASSERT_TRUE(result);
  7683. }
  7684. }
  7685. ASSERT_EQ(data, decompressed_data);
  7686. }
  7687. TEST(GzipDecompressor, DeflateDecompression) {
  7688. std::string original_text = "Raw deflate without gzip";
  7689. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7690. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7691. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7692. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7693. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7694. std::string decompressed_data;
  7695. {
  7696. httplib::detail::gzip_decompressor decompressor;
  7697. bool result = decompressor.decompress(
  7698. compressed_data.data(), compressed_data.size(),
  7699. [&](const char *decompressed_data_chunk,
  7700. size_t decompressed_data_chunk_size) {
  7701. decompressed_data.insert(decompressed_data.size(),
  7702. decompressed_data_chunk,
  7703. decompressed_data_chunk_size);
  7704. return true;
  7705. });
  7706. ASSERT_TRUE(result);
  7707. }
  7708. ASSERT_EQ(original_text, decompressed_data);
  7709. }
  7710. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7711. std::string original_text = "Raw deflate without gzip";
  7712. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7713. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7714. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7715. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7716. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7717. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7718. std::string decompressed_data;
  7719. {
  7720. httplib::detail::gzip_decompressor decompressor;
  7721. bool result = decompressor.decompress(
  7722. compressed_data.data(), compressed_data.size(),
  7723. [&](const char *decompressed_data_chunk,
  7724. size_t decompressed_data_chunk_size) {
  7725. decompressed_data.insert(decompressed_data.size(),
  7726. decompressed_data_chunk,
  7727. decompressed_data_chunk_size);
  7728. return true;
  7729. });
  7730. ASSERT_TRUE(result);
  7731. }
  7732. ASSERT_EQ(original_text, decompressed_data);
  7733. }
  7734. #endif
  7735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7736. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7737. Headers headers;
  7738. headers.emplace("Accept-Encoding", "br");
  7739. auto res = cli_.Get("/streamed-chunked", headers);
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ(std::string("123456789"), res->body);
  7743. }
  7744. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7745. Headers headers;
  7746. headers.emplace("Accept-Encoding", "br");
  7747. auto res = cli_.Get("/streamed-chunked2", headers);
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. EXPECT_EQ(std::string("123456789"), res->body);
  7751. }
  7752. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7753. cli_.set_compress(true);
  7754. auto res = cli_.Put(
  7755. "/put", 3,
  7756. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7757. sink.os << "PUT";
  7758. return true;
  7759. },
  7760. "text/plain");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("PUT", res->body);
  7764. }
  7765. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7766. cli_.set_compress(true);
  7767. auto res = cli_.Put(
  7768. "/put",
  7769. [](size_t /*offset*/, DataSink &sink) {
  7770. sink.os << "PUT";
  7771. sink.done();
  7772. return true;
  7773. },
  7774. "text/plain");
  7775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7776. EXPECT_EQ(StatusCode::OK_200, res->status);
  7777. EXPECT_EQ("PUT", res->body);
  7778. }
  7779. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7780. cli_.set_compress(true);
  7781. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7783. EXPECT_EQ(StatusCode::OK_200, res->status);
  7784. EXPECT_EQ(LARGE_DATA, res->body);
  7785. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7786. }
  7787. #endif
  7788. TEST_F(ServerTest, Patch) {
  7789. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. EXPECT_EQ(StatusCode::OK_200, res->status);
  7792. EXPECT_EQ("PATCH", res->body);
  7793. }
  7794. TEST_F(ServerTest, Delete) {
  7795. auto res = cli_.Delete("/delete");
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("DELETE", res->body);
  7799. }
  7800. TEST_F(ServerTest, DeleteContentReceiver) {
  7801. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("content", res->body);
  7805. }
  7806. TEST_F(ServerTest, Options) {
  7807. auto res = cli_.Options("*");
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7811. EXPECT_TRUE(res->body.empty());
  7812. }
  7813. TEST_F(ServerTest, URL) {
  7814. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST_F(ServerTest, ArrayParam) {
  7819. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. }
  7823. TEST_F(ServerTest, ArrayParamValues) {
  7824. auto res =
  7825. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. }
  7829. TEST_F(ServerTest, NoMultipleHeaders) {
  7830. Headers headers = {{"Content-Length", "5"}};
  7831. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7832. "text/plain");
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(StatusCode::OK_200, res->status);
  7835. }
  7836. TEST_F(ServerTest, PostContentReceiver) {
  7837. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7839. ASSERT_EQ(StatusCode::OK_200, res->status);
  7840. ASSERT_EQ("content", res->body);
  7841. }
  7842. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7843. UploadFormDataItems items = {
  7844. {"text1", "text default", "", ""},
  7845. {"text2", "aωb", "", ""},
  7846. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7847. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7848. {"file3", "", "", "application/octet-stream"},
  7849. };
  7850. auto res = cli_.Post("/content_receiver", items);
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::OK_200, res->status);
  7853. }
  7854. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7855. UploadFormDataItems items = {
  7856. {"text1", "text default", "", ""},
  7857. {"text2", "aωb", "", ""},
  7858. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7859. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7860. {"file3", "", "", "application/octet-stream"},
  7861. };
  7862. auto boundary = std::string("+++++");
  7863. std::string body;
  7864. for (const auto &item : items) {
  7865. body += "--" + boundary + "\r\n";
  7866. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7867. if (!item.filename.empty()) {
  7868. body += "; filename=\"" + item.filename + "\"";
  7869. }
  7870. body += "\r\n";
  7871. if (!item.content_type.empty()) {
  7872. body += "Content-Type: " + item.content_type + "\r\n";
  7873. }
  7874. body += "\r\n";
  7875. body += item.content + "\r\n";
  7876. }
  7877. body += "--" + boundary + "--\r\n";
  7878. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7879. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. }
  7883. TEST(MultipartFormDataTest, FieldEscaping) {
  7884. Server svr;
  7885. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7886. const ContentReader &content_reader) {
  7887. ASSERT_TRUE(req.is_multipart_form_data());
  7888. std::vector<FormData> received;
  7889. content_reader(
  7890. [&](const FormData &file) {
  7891. received.push_back(file);
  7892. return true;
  7893. },
  7894. [&](const char *data, size_t data_length) {
  7895. received.back().content.append(data, data_length);
  7896. return true;
  7897. });
  7898. // '"', CR and LF in names and filenames are escaped following the
  7899. // WHATWG HTML standard, so each part still parses as a single part
  7900. // with no injected headers. Content types get CR/LF escaped too,
  7901. // while '"' (legal there, e.g. quoted charset) is preserved.
  7902. ASSERT_EQ(4U, received.size());
  7903. EXPECT_EQ("na%22me", received[0].name);
  7904. EXPECT_EQ("quoted name", received[0].content);
  7905. EXPECT_EQ("file", received[1].name);
  7906. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7907. received[1].filename);
  7908. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7909. EXPECT_EQ("injected", received[1].content);
  7910. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7911. EXPECT_EQ("my%22file.txt", received[2].filename);
  7912. EXPECT_EQ("cr lf name", received[2].content);
  7913. EXPECT_EQ("typed", received[3].name);
  7914. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7915. received[3].content_type);
  7916. EXPECT_EQ("typed content", received[3].content);
  7917. });
  7918. auto port = svr.bind_to_any_port("localhost");
  7919. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. t.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. Client cli("localhost", port);
  7927. UploadFormDataItems items = {
  7928. {"na\"me", "quoted name", "", ""},
  7929. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7930. "application/octet-stream"},
  7931. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7932. {"typed", "typed content", "",
  7933. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7934. };
  7935. auto res = cli.Post("/post", items);
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. }
  7939. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7940. const UploadFormDataItems items = {
  7941. {"name1", "Content 1", "", ""},
  7942. {"name2", "Content 2", "file2.txt", "text/plain"},
  7943. };
  7944. Server svr;
  7945. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7946. const ContentReader &content_reader) {
  7947. ASSERT_TRUE(req.is_multipart_form_data());
  7948. std::vector<FormData> received;
  7949. content_reader(
  7950. [&](const FormData &file) {
  7951. received.push_back(file);
  7952. return true;
  7953. },
  7954. [&](const char *data, size_t data_length) {
  7955. received.back().content.append(data, data_length);
  7956. return true;
  7957. });
  7958. ASSERT_EQ(2U, received.size());
  7959. EXPECT_EQ("name1", received[0].name);
  7960. EXPECT_EQ("Content 1", received[0].content);
  7961. EXPECT_EQ("name2", received[1].name);
  7962. EXPECT_EQ("Content 2", received[1].content);
  7963. EXPECT_EQ("file2.txt", received[1].filename);
  7964. EXPECT_EQ("text/plain", received[1].content_type);
  7965. });
  7966. auto port = svr.bind_to_any_port("localhost");
  7967. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. t.join();
  7971. ASSERT_FALSE(svr.is_running());
  7972. });
  7973. svr.wait_until_ready();
  7974. Client cli("localhost", port);
  7975. // Whole-body serialization with a generated boundary
  7976. {
  7977. MultipartFormDataWriter writer;
  7978. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7979. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7980. writer.content_type());
  7981. auto body = writer.serialize(items);
  7982. EXPECT_EQ(body.size(), writer.content_length(items));
  7983. auto res = cli.Post("/post", body, writer.content_type());
  7984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7985. EXPECT_EQ(StatusCode::OK_200, res->status);
  7986. }
  7987. // Per-part framing with a custom boundary via a content provider
  7988. {
  7989. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7990. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7991. MultipartFormDataWriter writer("custom-boundary_123");
  7992. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7993. std::string body;
  7994. for (const auto &item : items) {
  7995. body += writer.item_begin(item);
  7996. body += item.content;
  7997. body += MultipartFormDataWriter::item_end();
  7998. }
  7999. body += writer.finish();
  8000. EXPECT_EQ(body.size(), writer.content_length(items));
  8001. auto res = cli.Post(
  8002. "/post", body.size(),
  8003. [&](size_t offset, size_t length, DataSink &sink) {
  8004. sink.write(body.data() + offset, length);
  8005. return true;
  8006. },
  8007. writer.content_type());
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::OK_200, res->status);
  8010. }
  8011. }
  8012. TEST_F(ServerTest, PostContentReceiverGzip) {
  8013. cli_.set_compress(true);
  8014. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8016. ASSERT_EQ(StatusCode::OK_200, res->status);
  8017. ASSERT_EQ("content", res->body);
  8018. }
  8019. TEST_F(ServerTest, PutContentReceiver) {
  8020. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. ASSERT_EQ("content", res->body);
  8024. }
  8025. TEST_F(ServerTest, PatchContentReceiver) {
  8026. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. ASSERT_EQ(StatusCode::OK_200, res->status);
  8029. ASSERT_EQ("content", res->body);
  8030. }
  8031. template <typename ClientType>
  8032. void TestWithHeadersAndContentReceiver(
  8033. ClientType &cli,
  8034. std::function<Result(ClientType &, const std::string &, const Headers &,
  8035. const std::string &, const std::string &,
  8036. ContentReceiver, DownloadProgress)>
  8037. request_func) {
  8038. Headers headers;
  8039. headers.emplace("X-Custom-Header", "test-value");
  8040. std::string received_body;
  8041. auto res = request_func(
  8042. cli, "/content_receiver", headers, "content", "application/json",
  8043. [&](const char *data, size_t data_length) {
  8044. received_body.append(data, data_length);
  8045. return true;
  8046. },
  8047. nullptr);
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. EXPECT_EQ("content", received_body);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiver<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiver<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.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiver<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.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverWithProgress(
  8093. ClientType &cli,
  8094. std::function<Result(ClientType &, const std::string &, const Headers &,
  8095. const std::string &, const std::string &,
  8096. ContentReceiver, DownloadProgress)>
  8097. request_func) {
  8098. Headers headers;
  8099. headers.emplace("X-Test-Header", "progress-test");
  8100. std::string received_body;
  8101. auto progress_called = false;
  8102. auto res = request_func(
  8103. cli, "/content_receiver", headers, "content", "text/plain",
  8104. [&](const char *data, size_t data_length) {
  8105. received_body.append(data, data_length);
  8106. return true;
  8107. },
  8108. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8109. progress_called = true;
  8110. return true;
  8111. });
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_EQ(StatusCode::OK_200, res->status);
  8114. EXPECT_EQ("content", received_body);
  8115. EXPECT_TRUE(progress_called);
  8116. }
  8117. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8118. #ifdef CPPHTTPLIB_SSL_ENABLED
  8119. using ClientT = SSLClient;
  8120. #else
  8121. using ClientT = Client;
  8122. #endif
  8123. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8124. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8125. const std::string &body, const std::string &content_type,
  8126. ContentReceiver receiver, DownloadProgress progress) {
  8127. return cli.Post(path, headers, body, content_type, receiver, progress);
  8128. });
  8129. }
  8130. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8131. #ifdef CPPHTTPLIB_SSL_ENABLED
  8132. using ClientT = SSLClient;
  8133. #else
  8134. using ClientT = Client;
  8135. #endif
  8136. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8137. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8138. const std::string &body, const std::string &content_type,
  8139. ContentReceiver receiver, DownloadProgress progress) {
  8140. return cli.Put(path, headers, body, content_type, receiver, progress);
  8141. });
  8142. }
  8143. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8144. #ifdef CPPHTTPLIB_SSL_ENABLED
  8145. using ClientT = SSLClient;
  8146. #else
  8147. using ClientT = Client;
  8148. #endif
  8149. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8150. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8151. const std::string &body, const std::string &content_type,
  8152. ContentReceiver receiver, DownloadProgress progress) {
  8153. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8154. });
  8155. }
  8156. template <typename ClientType>
  8157. void TestWithHeadersAndContentReceiverError(
  8158. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8159. const Headers &, const std::string &,
  8160. const std::string &, ContentReceiver)>
  8161. request_func) {
  8162. Headers headers;
  8163. headers.emplace("X-Error-Test", "true");
  8164. std::string received_body;
  8165. auto receiver_failed = false;
  8166. auto res =
  8167. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8168. [&](const char *data, size_t data_length) {
  8169. received_body.append(data, data_length);
  8170. receiver_failed = true;
  8171. return false;
  8172. });
  8173. ASSERT_FALSE(res);
  8174. EXPECT_TRUE(receiver_failed);
  8175. }
  8176. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8177. #ifdef CPPHTTPLIB_SSL_ENABLED
  8178. using ClientT = SSLClient;
  8179. #else
  8180. using ClientT = Client;
  8181. #endif
  8182. TestWithHeadersAndContentReceiverError<ClientT>(
  8183. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8184. const std::string &body, const std::string &content_type,
  8185. ContentReceiver receiver) {
  8186. return cli.Post(path, headers, body, content_type, receiver);
  8187. });
  8188. }
  8189. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8190. #ifdef CPPHTTPLIB_SSL_ENABLED
  8191. using ClientT = SSLClient;
  8192. #else
  8193. using ClientT = Client;
  8194. #endif
  8195. TestWithHeadersAndContentReceiverError<ClientT>(
  8196. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8197. const std::string &body, const std::string &content_type,
  8198. ContentReceiver receiver) {
  8199. return cli.Put(path, headers, body, content_type, receiver);
  8200. });
  8201. }
  8202. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8203. #ifdef CPPHTTPLIB_SSL_ENABLED
  8204. using ClientT = SSLClient;
  8205. #else
  8206. using ClientT = Client;
  8207. #endif
  8208. TestWithHeadersAndContentReceiverError<ClientT>(
  8209. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8210. const std::string &body, const std::string &content_type,
  8211. ContentReceiver receiver) {
  8212. return cli.Patch(path, headers, body, content_type, receiver);
  8213. });
  8214. }
  8215. TEST_F(ServerTest, PostQueryStringAndBody) {
  8216. auto res =
  8217. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. ASSERT_EQ(StatusCode::OK_200, res->status);
  8220. }
  8221. TEST_F(ServerTest, HTTP2Magic) {
  8222. Request req;
  8223. req.method = "PRI";
  8224. req.path = "*";
  8225. req.body = "SM";
  8226. auto res = std::make_shared<Response>();
  8227. auto error = Error::Success;
  8228. auto ret = cli_.send(req, *res, error);
  8229. ASSERT_TRUE(ret);
  8230. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8231. }
  8232. TEST_F(ServerTest, KeepAlive) {
  8233. auto res = cli_.Get("/hi");
  8234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8237. EXPECT_EQ("Hello World!", res->body);
  8238. res = cli_.Get("/hi");
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::OK_200, res->status);
  8241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8242. EXPECT_EQ("Hello World!", res->body);
  8243. res = cli_.Get("/hi");
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ(StatusCode::OK_200, res->status);
  8246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8247. EXPECT_EQ("Hello World!", res->body);
  8248. res = cli_.Get("/not-exist");
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8251. res = cli_.Post("/empty", "", "text/plain");
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8255. EXPECT_EQ("empty", res->body);
  8256. EXPECT_EQ("close", res->get_header_value("Connection"));
  8257. res = cli_.Post(
  8258. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8259. "text/plain");
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8263. EXPECT_EQ("empty", res->body);
  8264. cli_.set_keep_alive(false);
  8265. res = cli_.Get("/last-request");
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("close", res->get_header_value("Connection"));
  8269. }
  8270. TEST_F(ServerTest, TooManyRedirect) {
  8271. cli_.set_follow_location(true);
  8272. auto res = cli_.Get("/redirect/0");
  8273. ASSERT_TRUE(!res);
  8274. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8275. }
  8276. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8277. Request req;
  8278. req.method = "FOOBAR";
  8279. req.path = "/hi";
  8280. cli_.set_keep_alive(true);
  8281. auto res = cli_.send(req);
  8282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8283. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8284. EXPECT_EQ("close", res->get_header_value("Connection"));
  8285. EXPECT_FALSE(cli_.is_socket_open());
  8286. }
  8287. TEST_F(ServerTest, CustomRouteReadsBody) {
  8288. const std::string xml =
  8289. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8290. Request req;
  8291. req.method = "PROPFIND";
  8292. req.path = "/dav/dir";
  8293. req.set_header("Depth", "1");
  8294. req.body = xml;
  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(xml, res->body);
  8299. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8300. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8301. }
  8302. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8303. Request req;
  8304. req.method = "PROPFIND";
  8305. req.path = "/dav/42";
  8306. auto res = cli_.send(req);
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8309. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8310. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8311. }
  8312. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8313. Request req;
  8314. req.method = "PROPFIND";
  8315. req.path = "/dav-re/123";
  8316. auto res = cli_.send(req);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8319. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8320. }
  8321. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8322. Request req;
  8323. req.method = "MKCOL";
  8324. req.path = "/dav-mkcol";
  8325. auto res = cli_.send(req);
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. EXPECT_EQ(StatusCode::Created_201, res->status);
  8328. }
  8329. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8330. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8331. Request req;
  8332. req.method = "REPORT";
  8333. req.path = "/dav-report";
  8334. req.body = xml;
  8335. auto res = cli_.send(req);
  8336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8337. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8338. EXPECT_EQ(xml, res->body);
  8339. }
  8340. // A content reader route must fire even when the request carries no body,
  8341. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8342. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8343. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8344. Request req;
  8345. req.method = "REPORT";
  8346. req.path = "/dav-report";
  8347. auto res = cli_.send(req);
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8350. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8351. }
  8352. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8353. Request req;
  8354. req.method = "PROPFIND";
  8355. req.path = "/not-dav";
  8356. auto res = cli_.send(req);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8359. }
  8360. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8361. Request req;
  8362. req.method = "UNLOCK";
  8363. req.path = "/dav/dir";
  8364. cli_.set_keep_alive(true);
  8365. auto res = cli_.send(req);
  8366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8367. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8368. EXPECT_EQ("close", res->get_header_value("Connection"));
  8369. EXPECT_FALSE(cli_.is_socket_open());
  8370. }
  8371. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8372. // The mount point serves this path, but only for GET and HEAD.
  8373. auto get_res = cli_.Get("/dir/index.html");
  8374. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8375. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8376. Request req;
  8377. req.method = "PROPFIND";
  8378. req.path = "/dir/index.html";
  8379. auto res = cli_.send(req);
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8382. }
  8383. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8384. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8385. cli_.set_keep_alive(true);
  8386. for (auto i = 0; i < 2; i++) {
  8387. Request req;
  8388. req.method = "PROPFIND";
  8389. req.path = "/dav/dir";
  8390. req.body = xml;
  8391. auto res = cli_.send(req);
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8394. EXPECT_EQ(xml, res->body);
  8395. EXPECT_TRUE(cli_.is_socket_open());
  8396. }
  8397. // A built-in method must still be served on the same connection.
  8398. cli_.set_keep_alive(false);
  8399. auto res = cli_.Get("/hi");
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("close", res->get_header_value("Connection"));
  8403. }
  8404. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8405. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8406. Request req;
  8407. req.method = "PROPFIND";
  8408. req.path = "/dav/dir";
  8409. req.set_header("Expect", "100-continue");
  8410. req.body = xml;
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ(xml, res->body);
  8415. }
  8416. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8418. TEST_F(ServerTest, Gzip) {
  8419. Headers headers;
  8420. headers.emplace("Accept-Encoding", "gzip, deflate");
  8421. auto res = cli_.Get("/compress", headers);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8425. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8426. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8427. "7890123456789012345678901234567890",
  8428. res->body);
  8429. EXPECT_EQ(StatusCode::OK_200, res->status);
  8430. }
  8431. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8432. Headers headers;
  8433. headers.emplace("Accept-Encoding", "gzip, deflate");
  8434. auto res = cli_.Get("/compress-with-charset", headers);
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8437. EXPECT_EQ("application/json; charset=utf-8",
  8438. res->get_header_value("Content-Type"));
  8439. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8440. "7890123456789012345678901234567890",
  8441. res->body);
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8445. Headers headers;
  8446. headers.emplace("Accept-Encoding", "");
  8447. auto res = cli_.Get("/compress", headers);
  8448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8449. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8451. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8452. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8453. "7890123456789012345678901234567890",
  8454. res->body);
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, GzipWithContentReceiver) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "gzip, deflate");
  8460. std::string body;
  8461. auto res =
  8462. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8463. EXPECT_EQ(100U, data_length);
  8464. body.append(data, data_length);
  8465. return true;
  8466. });
  8467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8468. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8470. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8471. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8472. "7890123456789012345678901234567890",
  8473. body);
  8474. EXPECT_EQ(StatusCode::OK_200, res->status);
  8475. }
  8476. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8477. Headers headers;
  8478. headers.emplace("Accept-Encoding", "gzip, deflate");
  8479. cli_.set_decompress(false);
  8480. auto res = cli_.Get("/compress", headers);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8484. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8485. EXPECT_EQ(33U, res->body.size());
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. }
  8488. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8489. Headers headers;
  8490. headers.emplace("Accept-Encoding", "");
  8491. std::string body;
  8492. auto res =
  8493. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8494. EXPECT_EQ(100U, data_length);
  8495. body.append(data, data_length);
  8496. return true;
  8497. });
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8501. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8503. "7890123456789012345678901234567890",
  8504. body);
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. TEST_F(ServerTest, NoGzip) {
  8508. Headers headers;
  8509. headers.emplace("Accept-Encoding", "gzip, deflate");
  8510. auto res = cli_.Get("/nocompress", headers);
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8513. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8514. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8515. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8516. "7890123456789012345678901234567890",
  8517. res->body);
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. }
  8520. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "gzip, deflate");
  8523. std::string body;
  8524. auto res = cli_.Get("/nocompress", headers,
  8525. [&](const char *data, size_t data_length) {
  8526. EXPECT_EQ(100U, data_length);
  8527. body.append(data, data_length);
  8528. return true;
  8529. });
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8532. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8533. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8534. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8535. "7890123456789012345678901234567890",
  8536. body);
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. }
  8539. TEST_F(ServerTest, MultipartFormDataGzip) {
  8540. UploadFormDataItems items = {
  8541. {"key1", "test", "", ""},
  8542. {"key2", "--abcdefg123", "", ""},
  8543. };
  8544. cli_.set_compress(true);
  8545. auto res = cli_.Post("/compress-multipart", items);
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. #endif
  8550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8551. // Static file compression is opt-in, so these run their own server rather than
  8552. // flipping it on for the shared ServerTest fixture, which would silently
  8553. // rewrite what every other static file test is asserting.
  8554. class StaticFileCompressionTest : public ::testing::Test {
  8555. protected:
  8556. void TearDown() override {
  8557. if (t_.joinable()) {
  8558. svr_.stop();
  8559. t_.join();
  8560. }
  8561. }
  8562. int start(const std::function<void(Server &)> &configure = nullptr) {
  8563. // Serves the same tree as a directory of build-time compressed assets
  8564. // would be served: the mount point names the coding the files are already
  8565. // stored in. Registered before "/" so it is the one that matches.
  8566. svr_.set_mount_point("/pre-encoded", "./www",
  8567. {{"Content-Encoding", "gzip"}});
  8568. svr_.set_mount_point("/", "./www");
  8569. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8570. res.set_file_content("./www/dir/index.html", "text/html");
  8571. });
  8572. svr_.Get("/pre-encoded-file-content",
  8573. [](const Request & /*req*/, Response &res) {
  8574. res.set_header("Content-Encoding", "gzip");
  8575. res.set_file_content("./www/dir/index.html", "text/html");
  8576. });
  8577. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8578. res.set_content_provider(
  8579. 6, "text/plain",
  8580. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8581. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8582. return true;
  8583. });
  8584. });
  8585. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8586. res.set_content_provider(
  8587. 1000, "text/plain",
  8588. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8589. if (offset < 100) {
  8590. std::string data(100, 'A');
  8591. sink.write(data.data(), data.size());
  8592. return true;
  8593. }
  8594. std::this_thread::sleep_for(std::chrono::seconds(2));
  8595. std::string data(900, 'B');
  8596. sink.write(data.data(), data.size());
  8597. return true;
  8598. });
  8599. });
  8600. if (configure) { configure(svr_); }
  8601. auto port = svr_.bind_to_any_port(HOST);
  8602. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8603. svr_.wait_until_ready();
  8604. return port;
  8605. }
  8606. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8607. // Every file under ./www except 1MB.txt is smaller than the default
  8608. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8609. // it out of the way.
  8610. static void enable_without_floor(Server &svr) {
  8611. svr.set_static_file_compression(true);
  8612. svr.set_static_file_compression_min_length(0);
  8613. }
  8614. Server svr_;
  8615. std::thread t_;
  8616. };
  8617. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8618. auto port = start();
  8619. Client cli(HOST, port);
  8620. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8624. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8625. EXPECT_EQ(1048576U, res->body.size());
  8626. }
  8627. TEST_F(StaticFileCompressionTest, MountPoint) {
  8628. auto port = start(enable);
  8629. Client cli(HOST, port);
  8630. cli.set_decompress(false);
  8631. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8633. EXPECT_EQ(StatusCode::OK_200, res->status);
  8634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8635. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8636. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8637. // The response stays self-delimiting: a length, not a chunked body.
  8638. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8639. EXPECT_EQ(std::to_string(res->body.size()),
  8640. res->get_header_value("Content-Length"));
  8641. EXPECT_LT(res->body.size(), 1048576U);
  8642. EXPECT_FALSE(res->body.empty());
  8643. }
  8644. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8645. auto port = start(enable);
  8646. Client cli(HOST, port);
  8647. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8649. EXPECT_EQ(StatusCode::OK_200, res->status);
  8650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8651. EXPECT_EQ(1048576U, res->body.size());
  8652. }
  8653. TEST_F(StaticFileCompressionTest, FileContent) {
  8654. auto port = start(enable_without_floor);
  8655. Client cli(HOST, port);
  8656. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8658. EXPECT_EQ(StatusCode::OK_200, res->status);
  8659. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8660. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8661. EXPECT_EQ(104U, res->body.size());
  8662. }
  8663. // A handler that serves an already-encoded file names the coding itself. The
  8664. // file-backed path decided its coding from Accept-Encoding and the content
  8665. // type alone, so it compressed the stored bytes a second time and appended a
  8666. // second Content-Encoding field line.
  8667. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8668. auto port = start(enable_without_floor);
  8669. Client cli(HOST, port);
  8670. cli.set_decompress(false);
  8671. auto res = cli.Get("/pre-encoded-file-content",
  8672. Headers{{"Accept-Encoding", "gzip"}});
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8677. // Vary belongs to a coding the server chose, and it chose none here.
  8678. EXPECT_FALSE(res->has_header("Vary"));
  8679. // The file travels exactly as it is stored on disk.
  8680. EXPECT_EQ(104U, res->body.size());
  8681. }
  8682. // The 1MB file clears the default floor, so this one runs the configuration a
  8683. // deployment would actually have.
  8684. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8685. auto port = start(enable);
  8686. Client cli(HOST, port);
  8687. cli.set_decompress(false);
  8688. auto res =
  8689. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8693. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8694. EXPECT_FALSE(res->has_header("Vary"));
  8695. EXPECT_EQ(1048576U, res->body.size());
  8696. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8697. }
  8698. TEST_F(StaticFileCompressionTest, Head) {
  8699. auto port = start(enable);
  8700. Client cli(HOST, port);
  8701. cli.set_decompress(false);
  8702. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8703. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8704. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8706. EXPECT_EQ(StatusCode::OK_200, res->status);
  8707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8708. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8709. // HEAD still reports the size a GET would return.
  8710. EXPECT_EQ(get->get_header_value("Content-Length"),
  8711. res->get_header_value("Content-Length"));
  8712. EXPECT_TRUE(res->body.empty());
  8713. }
  8714. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8715. auto port = start(enable);
  8716. Client cli(HOST, port);
  8717. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8718. {"Accept-Encoding", "gzip"}});
  8719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8721. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8722. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8723. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8724. EXPECT_EQ("cd", res->body);
  8725. }
  8726. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8727. auto port = start(enable);
  8728. Client cli(HOST, port);
  8729. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8733. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8734. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8735. }
  8736. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8737. auto port = start(enable);
  8738. Client cli(HOST, port);
  8739. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::OK_200, res->status);
  8742. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8743. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8744. EXPECT_TRUE(res->body.empty());
  8745. }
  8746. TEST_F(StaticFileCompressionTest, MinLength) {
  8747. auto port = start(enable);
  8748. Client cli(HOST, port);
  8749. // 104 bytes, well under the default floor. Compressing it would add the
  8750. // gzip header and trailer to a body that already fits in one packet.
  8751. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8753. EXPECT_EQ(StatusCode::OK_200, res->status);
  8754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8755. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8756. }
  8757. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8758. auto port = start([](Server &svr) {
  8759. svr.set_static_file_compression(true);
  8760. svr.set_static_file_compression_min_length(1);
  8761. });
  8762. Client cli(HOST, port);
  8763. cli.set_decompress(false);
  8764. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8767. // A 9-byte file comes back larger than it went in, because gzip's header and
  8768. // trailer outweigh anything deflate can save. That is the end of the range
  8769. // the floor exists to keep out.
  8770. EXPECT_GT(res->body.size(), 9U);
  8771. }
  8772. TEST_F(StaticFileCompressionTest, MaxLength) {
  8773. auto port = start([](Server &svr) {
  8774. svr.set_static_file_compression(true);
  8775. svr.set_static_file_compression_min_length(0);
  8776. svr.set_static_file_compression_max_length(1024);
  8777. });
  8778. Client cli(HOST, port);
  8779. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8780. // defines `small` as a macro on Windows.
  8781. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8782. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8783. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8784. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8785. // Under it: compressed.
  8786. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8787. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8788. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8789. }
  8790. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8791. auto port = start(enable_without_floor);
  8792. Client cli(HOST, port);
  8793. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8794. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8795. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8796. auto identity_etag = identity->get_header_value("ETag");
  8797. ASSERT_FALSE(identity_etag.empty());
  8798. auto gzipped =
  8799. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8800. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8801. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8802. auto gzip_etag = gzipped->get_header_value("ETag");
  8803. ASSERT_FALSE(gzip_etag.empty());
  8804. // Two representations, two validators.
  8805. EXPECT_NE(identity_etag, gzip_etag);
  8806. // Each one revalidates against the request that would produce it...
  8807. auto fresh =
  8808. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8809. {"If-None-Match", gzip_etag}});
  8810. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8811. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8812. auto fresh_identity =
  8813. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8814. {"If-None-Match", identity_etag}});
  8815. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8816. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8817. // ...and not against the other representation.
  8818. auto crossed =
  8819. cli.Get("/dir/index.html",
  8820. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8821. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8822. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8823. }
  8824. // The opt-in covers responses the server reads off disk itself. A caller's own
  8825. // known-length provider keeps its Content-Length and, more importantly, keeps
  8826. // delivering incrementally: routing it through a compressor would hold every
  8827. // write back until zlib's window filled.
  8828. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8829. auto port = start(enable);
  8830. Client cli(HOST, port);
  8831. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8835. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("aaabbb", res->body);
  8837. }
  8838. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8839. auto port = start(enable);
  8840. Client cli(HOST, port);
  8841. cli.set_read_timeout(1, 0);
  8842. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8843. Headers{{"Accept-Encoding", "gzip"}});
  8844. ASSERT_TRUE(handle.is_valid());
  8845. // The provider writes 100 bytes and then stalls for longer than the read
  8846. // timeout. Those first bytes have to arrive anyway: run the response through
  8847. // a compressor and zlib holds them until its window fills, so the read would
  8848. // come back empty instead.
  8849. char buf[256];
  8850. auto n = handle.read(buf, sizeof(buf));
  8851. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8852. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8853. }
  8854. #endif
  8855. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8856. TEST_F(ServerTest, Brotli) {
  8857. Headers headers;
  8858. headers.emplace("Accept-Encoding", "br");
  8859. auto res = cli_.Get("/compress", headers);
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8865. "7890123456789012345678901234567890",
  8866. res->body);
  8867. EXPECT_EQ(StatusCode::OK_200, res->status);
  8868. }
  8869. #endif
  8870. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8871. TEST_F(ServerTest, Zstd) {
  8872. Headers headers;
  8873. headers.emplace("Accept-Encoding", "zstd");
  8874. auto res = cli_.Get("/compress", headers);
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8878. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8879. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8880. "7890123456789012345678901234567890",
  8881. res->body);
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. }
  8884. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8885. Headers headers;
  8886. headers.emplace("Accept-Encoding", "");
  8887. auto res = cli_.Get("/compress", headers);
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8890. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8891. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8893. "7890123456789012345678901234567890",
  8894. res->body);
  8895. EXPECT_EQ(StatusCode::OK_200, res->status);
  8896. }
  8897. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8898. Headers headers;
  8899. headers.emplace("Accept-Encoding", "zstd");
  8900. std::string body;
  8901. auto res =
  8902. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8903. EXPECT_EQ(100U, data_length);
  8904. body.append(data, data_length);
  8905. return true;
  8906. });
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8910. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8912. "7890123456789012345678901234567890",
  8913. body);
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8917. Headers headers;
  8918. headers.emplace("Accept-Encoding", "zstd");
  8919. cli_.set_decompress(false);
  8920. auto res = cli_.Get("/compress", headers);
  8921. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8922. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8923. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8924. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8926. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8928. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8929. EXPECT_EQ(StatusCode::OK_200, res->status);
  8930. ASSERT_EQ(26U, res->body.size());
  8931. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8932. 0);
  8933. }
  8934. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8935. Headers headers;
  8936. headers.emplace("Accept-Encoding", "");
  8937. std::string body;
  8938. auto res =
  8939. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8940. EXPECT_EQ(100U, data_length);
  8941. body.append(data, data_length);
  8942. return true;
  8943. });
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8947. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8948. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8949. "7890123456789012345678901234567890",
  8950. body);
  8951. EXPECT_EQ(StatusCode::OK_200, res->status);
  8952. }
  8953. TEST_F(ServerTest, NoZstd) {
  8954. Headers headers;
  8955. headers.emplace("Accept-Encoding", "zstd");
  8956. auto res = cli_.Get("/nocompress", headers);
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8959. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8960. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8962. "7890123456789012345678901234567890",
  8963. res->body);
  8964. EXPECT_EQ(StatusCode::OK_200, res->status);
  8965. }
  8966. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8967. Headers headers;
  8968. headers.emplace("Accept-Encoding", "zstd");
  8969. std::string body;
  8970. auto res = cli_.Get("/nocompress", headers,
  8971. [&](const char *data, size_t data_length) {
  8972. EXPECT_EQ(100U, data_length);
  8973. body.append(data, data_length);
  8974. return true;
  8975. });
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8978. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8979. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8980. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8981. "7890123456789012345678901234567890",
  8982. body);
  8983. EXPECT_EQ(StatusCode::OK_200, res->status);
  8984. }
  8985. // TODO: How to enable zstd ??
  8986. TEST_F(ServerTest, MultipartFormDataZstd) {
  8987. UploadFormDataItems items = {
  8988. {"key1", "test", "", ""},
  8989. {"key2", "--abcdefg123", "", ""},
  8990. };
  8991. Headers headers;
  8992. headers.emplace("Accept-Encoding", "zstd");
  8993. cli_.set_compress(true);
  8994. auto res = cli_.Post("/compress-multipart", headers, items);
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. }
  8998. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8999. Headers headers;
  9000. headers.emplace("Accept-Encoding", "zstd");
  9001. cli_.set_compress(true);
  9002. auto res = cli_.Put(
  9003. "/put", headers, 3,
  9004. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9005. sink.os << "PUT";
  9006. return true;
  9007. },
  9008. "text/plain");
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::OK_200, res->status);
  9011. EXPECT_EQ("PUT", res->body);
  9012. }
  9013. // Pre-compression logging tests
  9014. TEST_F(ServerTest, PreCompressionLogging) {
  9015. // Test data for compression (matches the actual /compress endpoint content)
  9016. const std::string test_content =
  9017. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9018. "3456789012345678901234567890";
  9019. // Variables to capture logging data
  9020. std::string pre_compression_body;
  9021. std::string pre_compression_content_type;
  9022. std::string pre_compression_content_encoding;
  9023. std::string post_compression_body;
  9024. std::string post_compression_content_type;
  9025. std::string post_compression_content_encoding;
  9026. // Set up pre-compression logger
  9027. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9028. const Response &res) {
  9029. pre_compression_body = res.body;
  9030. pre_compression_content_type = res.get_header_value("Content-Type");
  9031. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9032. });
  9033. // Set up post-compression logger
  9034. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9035. post_compression_body = res.body;
  9036. post_compression_content_type = res.get_header_value("Content-Type");
  9037. post_compression_content_encoding =
  9038. res.get_header_value("Content-Encoding");
  9039. });
  9040. // Test with gzip compression
  9041. Headers headers;
  9042. headers.emplace("Accept-Encoding", "gzip");
  9043. auto res = cli_.Get("/compress", headers);
  9044. // Verify response was compressed
  9045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9046. EXPECT_EQ(StatusCode::OK_200, res->status);
  9047. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9048. // Verify pre-compression logger captured uncompressed content
  9049. EXPECT_EQ(test_content, pre_compression_body);
  9050. EXPECT_EQ("text/plain", pre_compression_content_type);
  9051. EXPECT_TRUE(pre_compression_content_encoding
  9052. .empty()); // No encoding header before compression
  9053. // Verify post-compression logger captured compressed content
  9054. EXPECT_NE(test_content,
  9055. post_compression_body); // Should be different after compression
  9056. EXPECT_EQ("text/plain", post_compression_content_type);
  9057. EXPECT_EQ("gzip", post_compression_content_encoding);
  9058. // Verify compressed content is smaller
  9059. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. std::string post_compression_body;
  9067. svr_.set_pre_compression_logger(
  9068. [&](const Request & /*req*/, const Response &res) {
  9069. pre_compression_body = res.body;
  9070. });
  9071. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9072. post_compression_body = res.body;
  9073. });
  9074. Headers headers;
  9075. headers.emplace("Accept-Encoding", "br");
  9076. auto res = cli_.Get("/compress", headers);
  9077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9078. EXPECT_EQ(StatusCode::OK_200, res->status);
  9079. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9080. // Verify pre-compression content is uncompressed
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. // Verify post-compression content is compressed
  9083. EXPECT_NE(test_content, post_compression_body);
  9084. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9085. }
  9086. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9087. const std::string test_content =
  9088. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9089. "3456789012345678901234567890";
  9090. std::string pre_compression_body;
  9091. std::string post_compression_body;
  9092. svr_.set_pre_compression_logger(
  9093. [&](const Request & /*req*/, const Response &res) {
  9094. pre_compression_body = res.body;
  9095. });
  9096. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9097. post_compression_body = res.body;
  9098. });
  9099. // Request without compression (use /nocompress endpoint)
  9100. Headers headers;
  9101. auto res = cli_.Get("/nocompress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ(StatusCode::OK_200, res->status);
  9104. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9105. // Pre-compression logger should not be called when no compression is applied
  9106. EXPECT_TRUE(
  9107. pre_compression_body.empty()); // Pre-compression logger not called
  9108. EXPECT_EQ(
  9109. test_content,
  9110. post_compression_body); // Post-compression logger captures final content
  9111. }
  9112. TEST_F(ServerTest, LoggerSeesContentLength) {
  9113. size_t logged_content_length = 0;
  9114. std::string logged_content_length_header;
  9115. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9116. logged_content_length = res.content_length_;
  9117. logged_content_length_header = res.get_header_value("Content-Length");
  9118. });
  9119. auto res = cli_.Get("/nocompress");
  9120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ(res->body.size(), logged_content_length);
  9123. EXPECT_EQ(std::to_string(logged_content_length),
  9124. logged_content_length_header);
  9125. }
  9126. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9127. const std::string test_content =
  9128. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9129. "3456789012345678901234567890";
  9130. std::string pre_compression_body;
  9131. bool pre_logger_called = false;
  9132. // Set only pre-compression logger
  9133. svr_.set_pre_compression_logger(
  9134. [&](const Request & /*req*/, const Response &res) {
  9135. pre_compression_body = res.body;
  9136. pre_logger_called = true;
  9137. });
  9138. Headers headers;
  9139. headers.emplace("Accept-Encoding", "gzip");
  9140. auto res = cli_.Get("/compress", headers);
  9141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9142. EXPECT_EQ(StatusCode::OK_200, res->status);
  9143. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9144. // Verify pre-compression logger was called
  9145. EXPECT_TRUE(pre_logger_called);
  9146. EXPECT_EQ(test_content, pre_compression_body);
  9147. }
  9148. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9149. {
  9150. // Test with Expect: 100-continue header - success case
  9151. // Server returns 100 Continue, client sends body, server returns 200 OK
  9152. Request req;
  9153. req.method = "POST";
  9154. req.path = "/post-large";
  9155. req.set_header("Expect", "100-continue");
  9156. req.body = LARGE_DATA;
  9157. Response res;
  9158. auto error = Error::Success;
  9159. cli_.set_keep_alive(true);
  9160. auto ret = cli_.send(req, res, error);
  9161. EXPECT_TRUE(ret);
  9162. EXPECT_EQ(StatusCode::OK_200, res.status);
  9163. EXPECT_EQ(LARGE_DATA, res.body);
  9164. }
  9165. {
  9166. // Test with Expect: 100-continue header - error case
  9167. // Client should not send the body when server returns an error
  9168. Request req;
  9169. req.method = "POST";
  9170. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9171. req.set_header("Expect", "100-continue");
  9172. req.body = LARGE_DATA;
  9173. Response res;
  9174. auto error = Error::Success;
  9175. auto start = std::chrono::high_resolution_clock::now();
  9176. cli_.set_keep_alive(true);
  9177. auto ret = cli_.send(req, res, error);
  9178. auto end = std::chrono::high_resolution_clock::now();
  9179. auto elapsed =
  9180. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9181. .count();
  9182. // With Expect: 100-continue, request completes successfully but with error
  9183. EXPECT_TRUE(ret);
  9184. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9185. EXPECT_EQ("close", res.get_header_value("Connection"));
  9186. EXPECT_FALSE(cli_.is_socket_open());
  9187. EXPECT_LE(elapsed, 2000);
  9188. }
  9189. {
  9190. // Send an extra GET request to ensure error recovery without hanging
  9191. Request req;
  9192. req.method = "GET";
  9193. req.path = "/hi";
  9194. auto start = std::chrono::high_resolution_clock::now();
  9195. auto res = cli_.send(req);
  9196. auto end = std::chrono::high_resolution_clock::now();
  9197. auto elapsed =
  9198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9199. .count();
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ(StatusCode::OK_200, res->status);
  9202. EXPECT_EQ("Hello World!", res->body);
  9203. EXPECT_LE(elapsed, 500);
  9204. }
  9205. }
  9206. TEST(ZstdDecompressor, ChunkedDecompression) {
  9207. std::string data;
  9208. for (size_t i = 0; i < 32 * 1024; ++i) {
  9209. data.push_back(static_cast<char>('a' + i % 26));
  9210. }
  9211. std::string compressed_data;
  9212. {
  9213. httplib::detail::zstd_compressor compressor;
  9214. bool result = compressor.compress(
  9215. data.data(), data.size(),
  9216. /*last=*/true,
  9217. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9218. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9219. compressed_data_size);
  9220. return true;
  9221. });
  9222. ASSERT_TRUE(result);
  9223. }
  9224. std::string decompressed_data;
  9225. {
  9226. httplib::detail::zstd_decompressor decompressor;
  9227. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9228. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9229. size_t chunk_size = 130;
  9230. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9231. chunk_begin += chunk_size) {
  9232. size_t current_chunk_size =
  9233. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9234. bool result = decompressor.decompress(
  9235. compressed_data.data() + chunk_begin, current_chunk_size,
  9236. [&](const char *decompressed_data_chunk,
  9237. size_t decompressed_data_chunk_size) {
  9238. decompressed_data.insert(decompressed_data.size(),
  9239. decompressed_data_chunk,
  9240. decompressed_data_chunk_size);
  9241. return true;
  9242. });
  9243. ASSERT_TRUE(result);
  9244. }
  9245. }
  9246. ASSERT_EQ(data, decompressed_data);
  9247. }
  9248. TEST(ZstdDecompressor, Decompress) {
  9249. std::string original_text = "Compressed with ZSTD";
  9250. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9251. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9252. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9253. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9254. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9255. std::string decompressed_data;
  9256. {
  9257. httplib::detail::zstd_decompressor decompressor;
  9258. bool result = decompressor.decompress(
  9259. compressed_data.data(), compressed_data.size(),
  9260. [&](const char *decompressed_data_chunk,
  9261. size_t decompressed_data_chunk_size) {
  9262. decompressed_data.insert(decompressed_data.size(),
  9263. decompressed_data_chunk,
  9264. decompressed_data_chunk_size);
  9265. return true;
  9266. });
  9267. ASSERT_TRUE(result);
  9268. }
  9269. ASSERT_EQ(original_text, decompressed_data);
  9270. }
  9271. #endif
  9272. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9273. // separate chunks so that the server sees each part in its own read(). Used to
  9274. // place a read boundary at a specific offset of a request body.
  9275. static bool send_request_in_parts(time_t read_timeout_sec,
  9276. const std::vector<std::string> &parts,
  9277. std::string *resp = nullptr,
  9278. int port = PORT) {
  9279. auto error = Error::Success;
  9280. auto client_sock = detail::create_client_socket(
  9281. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9282. /*connection_timeout_sec=*/5, 0,
  9283. /*read_timeout_sec=*/5, 0,
  9284. /*write_timeout_sec=*/5, 0, std::string(), error);
  9285. if (client_sock == INVALID_SOCKET) { return false; }
  9286. auto ret = detail::process_client_socket(
  9287. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9288. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9289. for (size_t i = 0; i < parts.size(); i++) {
  9290. const auto &part = parts[i];
  9291. if (part.size() !=
  9292. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9293. return false;
  9294. }
  9295. if (i + 1 < parts.size()) {
  9296. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9297. }
  9298. }
  9299. char buf[512];
  9300. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9301. while (line_reader.getline()) {
  9302. if (resp) { *resp += line_reader.ptr(); }
  9303. }
  9304. return true;
  9305. });
  9306. detail::close_socket(client_sock);
  9307. return ret;
  9308. }
  9309. // Sends a raw request to a server listening at HOST:PORT.
  9310. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9311. std::string *resp = nullptr, int port = PORT) {
  9312. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9313. }
  9314. #ifdef CPPHTTPLIB_SSL_ENABLED
  9315. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9317. ASSERT_TRUE(svr.is_valid());
  9318. svr.set_read_timeout(1, 0);
  9319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9320. auto se = detail::scope_exit([&] {
  9321. svr.stop();
  9322. t.join();
  9323. ASSERT_FALSE(svr.is_running());
  9324. });
  9325. svr.wait_until_ready();
  9326. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9327. // keeps each wait well within the read timeout. The server gives up a
  9328. // second in, so the bytes sent after that fail.
  9329. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9330. parts.resize(26, std::string(1, '\0'));
  9331. EXPECT_FALSE(send_request_in_parts(5, parts));
  9332. }
  9333. #endif
  9334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9335. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9336. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9337. const std::vector<std::string> &parts,
  9338. std::string *resp = nullptr,
  9339. int port = PORT) {
  9340. auto error = Error::Success;
  9341. auto sock = detail::create_client_socket(
  9342. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9343. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9344. /*write_timeout_sec=*/5, 0, std::string(), error);
  9345. if (sock == INVALID_SOCKET) { return false; }
  9346. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9347. auto ctx = SSL_CTX_new(TLS_client_method());
  9348. auto ssl = SSL_new(ctx);
  9349. auto ssl_se = detail::scope_exit([&] {
  9350. SSL_free(ssl);
  9351. SSL_CTX_free(ctx);
  9352. });
  9353. SSL_set_fd(ssl, static_cast<int>(sock));
  9354. if (SSL_connect(ssl) != 1) { return false; }
  9355. for (size_t i = 0; i < parts.size(); i++) {
  9356. const auto &part = parts[i];
  9357. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9358. static_cast<int>(part.size())) {
  9359. return false;
  9360. }
  9361. if (i + 1 < parts.size()) {
  9362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9363. }
  9364. }
  9365. char buf[512];
  9366. int n;
  9367. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9368. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9369. }
  9370. return true;
  9371. }
  9372. #endif
  9373. // The request line, then a header value a byte at a time.
  9374. static std::vector<std::string> slow_request_head_parts() {
  9375. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9376. parts.resize(26, "a");
  9377. parts.emplace_back("\r\n\r\n");
  9378. return parts;
  9379. }
  9380. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9381. // within the one-second read timeout. The server gives up a second in, before
  9382. // the head is complete.
  9383. static void
  9384. expect_slow_request_head_dropped(Server &svr,
  9385. const std::function<std::string()> &send) {
  9386. std::atomic<bool> handled(false);
  9387. svr.Get("/", [&](const Request &, Response &res) {
  9388. handled = true;
  9389. res.set_content("ok", "text/plain");
  9390. });
  9391. svr.set_read_timeout(1, 0);
  9392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9393. auto se = detail::scope_exit([&] {
  9394. svr.stop();
  9395. t.join();
  9396. ASSERT_FALSE(svr.is_running());
  9397. });
  9398. svr.wait_until_ready();
  9399. auto resp = send();
  9400. EXPECT_FALSE(handled);
  9401. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9402. }
  9403. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9404. Server svr;
  9405. expect_slow_request_head_dropped(svr, [] {
  9406. std::string resp;
  9407. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9408. return resp;
  9409. });
  9410. }
  9411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9412. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9414. ASSERT_TRUE(svr.is_valid());
  9415. expect_slow_request_head_dropped(svr, [] {
  9416. std::string resp;
  9417. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9418. return resp;
  9419. });
  9420. }
  9421. #endif
  9422. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9423. Server svr;
  9424. std::string header_value;
  9425. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9426. header_value = req.get_header_value("foo");
  9427. res.set_content("ok", "text/plain");
  9428. });
  9429. thread t = thread([&] { svr.listen(HOST, PORT); });
  9430. auto se = detail::scope_exit([&] {
  9431. svr.stop();
  9432. t.join();
  9433. ASSERT_FALSE(svr.is_running());
  9434. });
  9435. svr.wait_until_ready();
  9436. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9437. // like characters are not treated the same - use vertical tab and escape.
  9438. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9439. "foo: \t \v bar \x1B\t \r\n"
  9440. "Connection: close\r\n"
  9441. "\r\n";
  9442. std::string res;
  9443. ASSERT_TRUE(send_request(5, req, &res));
  9444. EXPECT_EQ(header_value, "");
  9445. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9446. }
  9447. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9448. Server svr;
  9449. std::string received;
  9450. svr.Get("/order", [&](const Request &req, Response &res) {
  9451. received = entries_to_string(req.headers);
  9452. res.set_content("ok", "text/plain");
  9453. });
  9454. auto port = svr.bind_to_any_port(HOST);
  9455. thread t = thread([&] { svr.listen_after_bind(); });
  9456. auto se = detail::scope_exit([&] {
  9457. svr.stop();
  9458. t.join();
  9459. ASSERT_FALSE(svr.is_running());
  9460. });
  9461. svr.wait_until_ready();
  9462. const std::string req = "GET /order HTTP/1.1\r\n"
  9463. "Host: localhost\r\n"
  9464. "X-First: 1\r\n"
  9465. "X-Dup: a\r\n"
  9466. "X-Second: 2\r\n"
  9467. "X-Dup: b\r\n"
  9468. "Connection: close\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(5, req, &res, port));
  9472. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9473. EXPECT_EQ(
  9474. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9475. received);
  9476. }
  9477. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9478. Server svr;
  9479. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9480. res.set_header("Set-Cookie", "first=1");
  9481. res.set_header("X-Between", "y");
  9482. res.set_header("Set-Cookie", "second=2");
  9483. res.set_content("ok", "text/plain");
  9484. });
  9485. auto port = svr.bind_to_any_port(HOST);
  9486. thread t = thread([&] { svr.listen_after_bind(); });
  9487. auto se = detail::scope_exit([&] {
  9488. svr.stop();
  9489. t.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. Client cli(HOST, port);
  9494. auto res = cli.Get("/cookies");
  9495. ASSERT_TRUE(res);
  9496. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9497. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9498. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9499. }
  9500. // A stream may send a byte at a time with a small extension on each chunk,
  9501. // however long it runs
  9502. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9503. Server svr;
  9504. svr.Post("/count", [](const Request &req, Response &res) {
  9505. res.set_content(std::to_string(req.body.size()), "text/plain");
  9506. });
  9507. auto port = svr.bind_to_any_port(HOST);
  9508. ASSERT_LT(0, port);
  9509. thread t = thread([&] { svr.listen_after_bind(); });
  9510. auto se = detail::scope_exit([&] {
  9511. svr.stop();
  9512. t.join();
  9513. ASSERT_FALSE(svr.is_running());
  9514. });
  9515. svr.wait_until_ready();
  9516. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9517. "\r\nTransfer-Encoding: chunked\r\n"
  9518. "Connection: close\r\n\r\n";
  9519. for (auto i = 0; i < 4096; i++) {
  9520. req += "1;a=b\r\nx\r\n";
  9521. }
  9522. req += "0\r\n\r\n";
  9523. std::string res;
  9524. ASSERT_TRUE(send_request(5, req, &res, port));
  9525. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9526. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9527. }
  9528. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9529. Server svr;
  9530. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9531. auto i = new int(0);
  9532. res.set_header("Trailer", "X-Safe, X-Reflected");
  9533. res.set_chunked_content_provider(
  9534. "text/plain",
  9535. [i](size_t /*offset*/, DataSink &sink) {
  9536. if (*i == 0) {
  9537. sink.os << "body";
  9538. } else {
  9539. Headers trailer;
  9540. // A valid trailer that must survive.
  9541. trailer.emplace("X-Safe", "safe");
  9542. // Attacker-controlled value carrying CR/LF (response splitting).
  9543. trailer.emplace("X-Reflected",
  9544. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9545. // Attacker-controlled name carrying CR/LF.
  9546. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9547. sink.done_with_trailer(trailer);
  9548. }
  9549. (*i)++;
  9550. return true;
  9551. },
  9552. [i](bool /*success*/) { delete i; });
  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-trailer 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. // Invalid trailers are dropped entirely, matching set_header().
  9573. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9574. // The valid trailer still passes through.
  9575. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9576. }
  9577. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9578. // A custom header writer gets only the fields the default one writes
  9579. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9580. std::string s;
  9581. for (const auto &h : hdrs) {
  9582. s += h.first + ": " + h.second + "\r\n";
  9583. }
  9584. s += "\r\n";
  9585. return strm.write(s.data(), s.size());
  9586. };
  9587. for (auto custom_writer : {false, true}) {
  9588. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9589. Server svr;
  9590. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9591. svr.set_post_routing_handler([](const Request &, Response &res) {
  9592. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9593. });
  9594. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9595. // res.headers is a public field an application can populate directly,
  9596. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9597. // A valid header that must survive.
  9598. res.headers.emplace("X-Safe", "safe");
  9599. // Attacker-controlled value carrying CR/LF (response splitting).
  9600. res.headers.emplace("X-Reflected",
  9601. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9602. // Attacker-controlled name carrying CR/LF.
  9603. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9604. res.set_content("body", "text/plain");
  9605. });
  9606. thread t = thread([&] { svr.listen(HOST, PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. ASSERT_FALSE(svr.is_running());
  9611. });
  9612. svr.wait_until_ready();
  9613. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9614. "Host: " + HOST +
  9615. "\r\n"
  9616. "Connection: close\r\n"
  9617. "\r\n";
  9618. std::string res;
  9619. ASSERT_TRUE(send_request(5, req, &res));
  9620. // The injected fields must not appear anywhere in the raw response.
  9621. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9622. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9623. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9624. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9625. // Invalid headers are dropped entirely, matching set_header().
  9626. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9627. // The valid header still passes through.
  9628. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9629. }
  9630. }
  9631. // Forward declaration: in split builds split.py strips `inline` and moves the
  9632. // definition into httplib.cc, so detail::write_request_line is not visible from
  9633. // the public httplib.h. Re-declaring it here lets the tests link against the
  9634. // symbol in both header-only and split builds.
  9635. namespace httplib {
  9636. namespace detail {
  9637. ssize_t write_request_line(Stream &strm, const std::string &method,
  9638. const std::string &path);
  9639. } // namespace detail
  9640. } // namespace httplib
  9641. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9642. // A well-formed target is written verbatim.
  9643. {
  9644. detail::BufferStream strm;
  9645. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9646. EXPECT_GT(n, 0);
  9647. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9648. }
  9649. // A target carrying CR/LF, SP or other control octets must be rejected
  9650. // before anything reaches the wire, otherwise it splits the request line and
  9651. // injects a header or a whole request.
  9652. const std::string evil_targets[] = {
  9653. "/a\r\nInjected: pwned",
  9654. "/a\rInjected",
  9655. "/a\nInjected",
  9656. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9657. "/a b",
  9658. "/a\tb",
  9659. "/a\x7f",
  9660. };
  9661. for (const auto &evil : evil_targets) {
  9662. detail::BufferStream strm;
  9663. auto n = detail::write_request_line(strm, "GET", evil);
  9664. EXPECT_LT(n, 0);
  9665. EXPECT_TRUE(strm.get_buffer().empty());
  9666. }
  9667. }
  9668. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9669. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9670. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9671. // target reaches write_request. The client must fail cleanly with
  9672. // Error::Write instead of putting a request-line-less, header-injecting
  9673. // request on the wire.
  9674. Server svr;
  9675. svr.Get("/a", [](const Request &, Response &res) {
  9676. res.set_content("ok", "text/plain");
  9677. });
  9678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. thread.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. });
  9684. svr.wait_until_ready();
  9685. {
  9686. Client cli(HOST, PORT);
  9687. cli.set_path_encode(false);
  9688. // The request is rejected before anything is written, so the connection
  9689. // stays silent and the subsequent response read would otherwise block for
  9690. // the full default read timeout. Shorten it -- the assertion is on the
  9691. // error, not the timeout.
  9692. cli.set_read_timeout(1, 0);
  9693. auto res = cli.Get("/a\r\nInjected: pwned");
  9694. EXPECT_FALSE(res);
  9695. EXPECT_EQ(Error::Write, res.error());
  9696. }
  9697. }
  9698. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9699. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9700. // including extension methods.
  9701. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9702. for (const auto &method : good_methods) {
  9703. detail::BufferStream strm;
  9704. auto n = detail::write_request_line(strm, method, "/");
  9705. EXPECT_GT(n, 0);
  9706. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9707. }
  9708. // A method carrying CR/LF would split the request line and smuggle a whole
  9709. // request ahead of the real one. A space or an empty method corrupts the
  9710. // request line. All must be rejected before anything reaches the wire.
  9711. const std::string evil_methods[] = {
  9712. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9713. "GET\r\nInjected: pwned",
  9714. "GET\r",
  9715. "GET\n",
  9716. "GE T",
  9717. "",
  9718. };
  9719. for (const auto &evil : evil_methods) {
  9720. detail::BufferStream strm;
  9721. auto n = detail::write_request_line(strm, evil, "/");
  9722. EXPECT_LT(n, 0);
  9723. EXPECT_TRUE(strm.get_buffer().empty());
  9724. }
  9725. }
  9726. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9727. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9728. // through Client::send must fail with Error::Write and no request, neither
  9729. // the smuggled one nor the real one, may reach the server.
  9730. Server svr;
  9731. std::atomic<int> request_count(0);
  9732. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9733. request_count++;
  9734. res.status = StatusCode::OK_200;
  9735. return Server::HandlerResponse::Handled;
  9736. });
  9737. auto port = svr.bind_to_any_port(HOST);
  9738. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9739. auto se = detail::scope_exit([&] {
  9740. svr.stop();
  9741. thread.join();
  9742. ASSERT_FALSE(svr.is_running());
  9743. });
  9744. svr.wait_until_ready();
  9745. {
  9746. Client cli(HOST, port);
  9747. const std::string evil_methods[] = {
  9748. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9749. "GE T",
  9750. "",
  9751. };
  9752. for (const auto &evil : evil_methods) {
  9753. Request req;
  9754. req.method = evil;
  9755. req.path = "/";
  9756. auto res = cli.send(req);
  9757. EXPECT_FALSE(res);
  9758. EXPECT_EQ(Error::Write, res.error());
  9759. }
  9760. auto handle =
  9761. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9762. EXPECT_FALSE(handle.is_valid());
  9763. EXPECT_EQ(Error::Write, handle.error);
  9764. // A valid request on the same client still goes through.
  9765. auto res = cli.Get("/");
  9766. ASSERT_TRUE(res);
  9767. EXPECT_EQ(StatusCode::OK_200, res->status);
  9768. }
  9769. EXPECT_EQ(1, request_count.load());
  9770. }
  9771. // Sends a raw request and verifies that there isn't a crash or exception.
  9772. static void test_raw_request(const std::string &req,
  9773. std::string *out = nullptr) {
  9774. Server svr;
  9775. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9776. res.set_content("ok", "text/plain");
  9777. });
  9778. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9779. res.set_content("ok", "text/plain");
  9780. });
  9781. svr.Get("/header_field_value_check",
  9782. [&](const Request & /*req*/, Response &res) {
  9783. res.set_content("ok", "text/plain");
  9784. });
  9785. svr.CustomRoute("PROPFIND", "/dav",
  9786. [&](const Request & /*req*/, Response &res) {
  9787. res.status = StatusCode::MultiStatus_207;
  9788. });
  9789. // Server read timeout must be longer than the client read timeout for the
  9790. // bug to reproduce, probably to force the server to process a request
  9791. // without a trailing blank line.
  9792. const time_t client_read_timeout_sec = 1;
  9793. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9794. bool listen_thread_ok = false;
  9795. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9796. auto se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. t.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. EXPECT_TRUE(listen_thread_ok);
  9801. });
  9802. svr.wait_until_ready();
  9803. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9804. }
  9805. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9806. // A certain header line causes an exception if the header property is parsed
  9807. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9808. test_raw_request(
  9809. "GET /hi HTTP/1.1\r\n"
  9810. " : "
  9811. " "
  9812. " ");
  9813. }
  9814. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9815. // A certain header line causes an exception if the header property *name* is
  9816. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9817. // greedy matcher and requires backtracking when there are a lot of ":"
  9818. // characters.
  9819. // This occurs with libc++ but not libstdc++.
  9820. test_raw_request(
  9821. "GET /hi HTTP/1.1\r\n"
  9822. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9823. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9824. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9825. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9826. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9827. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9828. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9829. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9830. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9831. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9832. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9833. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9834. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9835. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9836. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9837. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9838. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9839. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9840. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9841. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9842. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9843. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9844. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9845. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9846. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9847. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9848. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9849. "&&&%%%");
  9850. }
  9851. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9852. // Make sure this doesn't crash the server.
  9853. // In a previous version of the header line regex, the "\r" rendered the line
  9854. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9855. // a new position where the leading white space ended and the field value
  9856. // began.
  9857. // The crash occurs with libc++ but not libstdc++.
  9858. test_raw_request("GET /hi HTTP/1.1\r\n"
  9859. "a:" +
  9860. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9861. "\r\n"
  9862. "\r\n");
  9863. }
  9864. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9865. const char *rejected[] = {
  9866. // RFC 9112 §3: one SP between the parts, and nothing else
  9867. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9868. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9869. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9870. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9871. // A request-target has no fragment
  9872. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9873. // An HTTP/1.1 request needs a Host
  9874. "GET /hi HTTP/1.1\r\n\r\n",
  9875. };
  9876. for (auto request : rejected) {
  9877. std::string out;
  9878. test_raw_request(request, &out);
  9879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9880. }
  9881. std::string out;
  9882. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9883. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9884. }
  9885. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9886. // RFC 9112 §6.1
  9887. const char *requests[] = {
  9888. "PUT /put_hi HTTP/1.1\r\n"
  9889. "Host: localhost\r\n"
  9890. "Content-Length: 0\r\n"
  9891. "Transfer-Encoding: chunked\r\n"
  9892. "\r\n"
  9893. "0\r\n\r\n",
  9894. "PUT /put_hi HTTP/1.0\r\n"
  9895. "Connection: keep-alive\r\n"
  9896. "Transfer-Encoding: chunked\r\n"
  9897. "\r\n"
  9898. "0\r\n\r\n",
  9899. };
  9900. for (auto request : requests) {
  9901. std::string out;
  9902. test_raw_request(request, &out);
  9903. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9904. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9905. }
  9906. }
  9907. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9908. std::string out;
  9909. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9910. "Content-Type: text/plain\r\n"
  9911. "Transfer-Encoding: chunked\r\n"
  9912. "\r\n"
  9913. "nothex\r\n",
  9914. &out);
  9915. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9916. }
  9917. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9918. std::string out;
  9919. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9920. "Content-Type: text/plain\r\n"
  9921. "Transfer-Encoding: chunked\r\n"
  9922. "\r\n"
  9923. "3\r\n"
  9924. "xyz\r\n"
  9925. "NaN\r\n",
  9926. &out);
  9927. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9928. }
  9929. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9930. std::string out;
  9931. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9932. "Content-Type: text/plain\r\n"
  9933. "Transfer-Encoding: chunked\r\n"
  9934. "\r\n"
  9935. // Length is too large for 64 bits.
  9936. "1ffffffffffffffff\r\n"
  9937. "xyz\r\n",
  9938. &out);
  9939. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9940. }
  9941. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9942. test_raw_request("GET /hi HTTP/1.1\r\n"
  9943. "Content-Type: text/plain\r\n\r");
  9944. }
  9945. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9946. std::string out;
  9947. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9948. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9949. }
  9950. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9951. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9952. std::string out;
  9953. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9954. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9955. }
  9956. }
  9957. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9958. std::string out;
  9959. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9960. "Host: localhost\r\n"
  9961. "Connection: close\r\n\r\n",
  9962. &out);
  9963. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9964. }
  9965. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9966. Server svr;
  9967. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9968. EXPECT_TRUE(!req.remote_addr.empty());
  9969. });
  9970. thread t = thread([&] { svr.listen(HOST, PORT); });
  9971. auto se = detail::scope_exit([&] {
  9972. svr.stop();
  9973. t.join();
  9974. ASSERT_FALSE(svr.is_running());
  9975. });
  9976. svr.wait_until_ready();
  9977. // Send an invalid request line to trigger Bad Request
  9978. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9979. std::string out;
  9980. ASSERT_TRUE(send_request(5, bad_req, &out));
  9981. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9982. }
  9983. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9984. // answered right away rather than blocking on a read that waits for EOF.
  9985. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9986. std::string out;
  9987. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9988. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9989. }
  9990. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9991. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9992. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9993. for (const auto *method : methods) {
  9994. Server svr;
  9995. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9996. EXPECT_FALSE(svr.is_valid()) << method;
  9997. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9998. }
  9999. }
  10000. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10001. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10002. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10003. for (const auto *method : methods) {
  10004. Server svr;
  10005. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10006. EXPECT_FALSE(svr.is_valid()) << method;
  10007. }
  10008. }
  10009. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10010. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10011. "COPY", "MOVE", "LOCK",
  10012. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10013. Server svr;
  10014. for (const auto *method : methods) {
  10015. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10016. }
  10017. EXPECT_TRUE(svr.is_valid());
  10018. }
  10019. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10020. Server svr;
  10021. svr.CustomRoute("POST", "/x",
  10022. [](const Request &, Response &, const ContentReader &) {});
  10023. EXPECT_FALSE(svr.is_valid());
  10024. }
  10025. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10026. Server svr;
  10027. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10028. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10029. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10030. EXPECT_FALSE(svr.is_valid());
  10031. }
  10032. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10033. Server svr;
  10034. auto captured = Error::Success;
  10035. svr.set_error_logger(
  10036. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10037. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10038. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10039. }
  10040. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10041. std::string out;
  10042. std::string request(
  10043. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10044. test_raw_request(request, &out);
  10045. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10046. }
  10047. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10048. std::string out;
  10049. std::string request(
  10050. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10051. test_raw_request(request, &out);
  10052. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10053. }
  10054. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10055. std::string out;
  10056. std::string request(
  10057. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10058. test_raw_request(request, &out);
  10059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10060. }
  10061. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10062. std::string out;
  10063. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10064. "Host: localhost\r\n"
  10065. "Test: \r\n\r\n",
  10066. &out);
  10067. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10068. }
  10069. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10070. Server svr;
  10071. std::string x_custom;
  10072. std::string cookie;
  10073. std::string xff;
  10074. std::string x_unicode;
  10075. std::string x_iis;
  10076. svr.Get("/check", [&](const Request &req, Response &res) {
  10077. x_custom = req.get_header_value("X-Custom");
  10078. cookie = req.get_header_value("Cookie");
  10079. xff = req.get_header_value("X-Forwarded-For");
  10080. x_unicode = req.get_header_value("X-Unicode");
  10081. x_iis = req.get_header_value("X-IIS");
  10082. res.set_content("ok", "text/plain");
  10083. });
  10084. thread t = thread([&] { svr.listen(HOST, PORT); });
  10085. auto se = detail::scope_exit([&] {
  10086. svr.stop();
  10087. t.join();
  10088. ASSERT_FALSE(svr.is_running());
  10089. });
  10090. svr.wait_until_ready();
  10091. const std::string req = "GET /check HTTP/1.1\r\n"
  10092. "Host: localhost\r\n"
  10093. "X-Custom: a%0D%0AInjected: b\r\n"
  10094. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10095. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10096. "X-Unicode: %E3%81%82\r\n"
  10097. "X-IIS: %u00E9\r\n"
  10098. "Connection: close\r\n"
  10099. "\r\n";
  10100. std::string res;
  10101. ASSERT_TRUE(send_request(5, req, &res));
  10102. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10103. // Every value must be returned verbatim (wire form), with no decoding.
  10104. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10105. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10106. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10107. EXPECT_EQ("%E3%81%82", x_unicode);
  10108. EXPECT_EQ("%u00E9", x_iis);
  10109. }
  10110. // Applications that previously relied on automatic percent-decoding can
  10111. // reproduce the old behavior by explicitly calling decode_path_component()
  10112. // or, for RFC 3986 conformance, decode_uri_component().
  10113. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10114. Server svr;
  10115. std::string decoded;
  10116. svr.Get("/check", [&](const Request &req, Response &res) {
  10117. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10118. res.set_content("ok", "text/plain");
  10119. });
  10120. thread t = thread([&] { svr.listen(HOST, PORT); });
  10121. auto se = detail::scope_exit([&] {
  10122. svr.stop();
  10123. t.join();
  10124. ASSERT_FALSE(svr.is_running());
  10125. });
  10126. svr.wait_until_ready();
  10127. const std::string req = "GET /check HTTP/1.1\r\n"
  10128. "Host: localhost\r\n"
  10129. "X-Custom: hello%20world\r\n"
  10130. "Connection: close\r\n"
  10131. "\r\n";
  10132. std::string res;
  10133. ASSERT_TRUE(send_request(5, req, &res));
  10134. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10135. EXPECT_EQ("hello world", decoded);
  10136. }
  10137. // Regression test for #2033. Browsers send Referer values that include
  10138. // percent-encoded characters such as %0A inside the URL. Decoding the
  10139. // header value would either trip the post-decode CR/LF/NUL guard (the
  10140. // original bug, returning 400) or, after that guard was relaxed, silently
  10141. // store a literal LF — both unacceptable. The wire form must round-trip.
  10142. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10143. Server svr;
  10144. std::string referer;
  10145. svr.Get("/check", [&](const Request &req, Response &res) {
  10146. referer = req.get_header_value("Referer");
  10147. res.set_content("ok", "text/plain");
  10148. });
  10149. thread t = thread([&] { svr.listen(HOST, PORT); });
  10150. auto se = detail::scope_exit([&] {
  10151. svr.stop();
  10152. t.join();
  10153. ASSERT_FALSE(svr.is_running());
  10154. });
  10155. svr.wait_until_ready();
  10156. const std::string req = "GET /check HTTP/1.1\r\n"
  10157. "Host: localhost\r\n"
  10158. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10159. "Connection: close\r\n"
  10160. "\r\n";
  10161. std::string res;
  10162. ASSERT_TRUE(send_request(5, req, &res));
  10163. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10164. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10165. }
  10166. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10167. Server svr;
  10168. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10169. res.set_header("Cache-Control", "no-cache");
  10170. res.set_chunked_content_provider(
  10171. "text/event-stream", [](size_t offset, DataSink &sink) {
  10172. std::string s = "data:";
  10173. s += std::to_string(offset);
  10174. s += "\n\n";
  10175. auto ret = sink.write(s.data(), s.size());
  10176. EXPECT_TRUE(ret);
  10177. std::this_thread::sleep_for(std::chrono::seconds(1));
  10178. return true;
  10179. });
  10180. });
  10181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10182. svr.wait_until_ready();
  10183. Client client(HOST, PORT);
  10184. const Headers headers = {{"Accept", "text/event-stream"}};
  10185. auto get_thread = std::thread([&client, &headers]() {
  10186. auto res = client.Get(
  10187. "/events", headers,
  10188. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10189. });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. get_thread.join();
  10193. listen_thread.join();
  10194. ASSERT_FALSE(svr.is_running());
  10195. });
  10196. // Give GET time to get a few messages.
  10197. std::this_thread::sleep_for(std::chrono::seconds(2));
  10198. }
  10199. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10200. httplib::Server svr;
  10201. svr.Post("/hi",
  10202. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10203. res.status = StatusCode::OK_200;
  10204. });
  10205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10206. svr.wait_until_ready();
  10207. Client cli(HOST, PORT);
  10208. auto res = cli.Post("/hi", "data", "text/plain");
  10209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. svr.stop();
  10212. thread.join();
  10213. ASSERT_FALSE(svr.is_running());
  10214. res = cli.Post("/hi", "data", "text/plain");
  10215. ASSERT_FALSE(res);
  10216. }
  10217. TEST(ServerStopTest, ListenFailure) {
  10218. Server svr;
  10219. auto t = thread([&]() {
  10220. auto ret = svr.listen("????", PORT);
  10221. EXPECT_FALSE(ret);
  10222. });
  10223. svr.wait_until_ready();
  10224. svr.stop();
  10225. t.join();
  10226. }
  10227. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10228. TEST(ServerStopTest, Decommision) {
  10229. Server svr;
  10230. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10231. for (int i = 0; i < 4; i++) {
  10232. auto is_even = !(i % 2);
  10233. std::thread t{[&] {
  10234. try {
  10235. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10236. if (is_even) {
  10237. throw std::runtime_error("Some thing that happens to go wrong.");
  10238. }
  10239. svr.listen(HOST, PORT);
  10240. } catch (...) { svr.decommission(); }
  10241. }};
  10242. svr.wait_until_ready();
  10243. // Server is up
  10244. {
  10245. Client cli(HOST, PORT);
  10246. auto res = cli.Get("/hi");
  10247. if (is_even) {
  10248. EXPECT_FALSE(res);
  10249. } else {
  10250. EXPECT_TRUE(res);
  10251. EXPECT_EQ("hi...", res->body);
  10252. }
  10253. }
  10254. svr.stop();
  10255. t.join();
  10256. // Server is down...
  10257. {
  10258. Client cli(HOST, PORT);
  10259. auto res = cli.Get("/hi");
  10260. EXPECT_FALSE(res);
  10261. }
  10262. }
  10263. }
  10264. #endif
  10265. // Helper function for string body upload progress tests
  10266. template <typename SetupHandler, typename ClientCall>
  10267. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10268. ClientCall &&client_call,
  10269. const string &body) {
  10270. Server svr;
  10271. setup_handler(svr);
  10272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10273. auto se = detail::scope_exit([&] {
  10274. svr.stop();
  10275. t.join();
  10276. });
  10277. svr.wait_until_ready();
  10278. Client cli(HOST, PORT);
  10279. vector<uint64_t> progress_values;
  10280. bool progress_called = false;
  10281. auto res =
  10282. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10283. progress_values.push_back(current);
  10284. progress_called = true;
  10285. return true;
  10286. });
  10287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10288. EXPECT_EQ(200, res->status);
  10289. EXPECT_TRUE(progress_called);
  10290. }
  10291. TEST(UploadProgressTest, PostStringBodyBasic) {
  10292. TestStringBodyUploadProgress(
  10293. [](Server &svr) {
  10294. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10295. res.set_content("received", "text/plain");
  10296. });
  10297. },
  10298. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10299. return cli.Post("/test", body, "text/plain", progress_callback);
  10300. },
  10301. "test data for upload progress");
  10302. }
  10303. TEST(UploadProgressTest, PutStringBodyBasic) {
  10304. TestStringBodyUploadProgress(
  10305. [](Server &svr) {
  10306. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10307. res.set_content("put received", "text/plain");
  10308. });
  10309. },
  10310. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10311. return cli.Put("/test", body, "text/plain", progress_callback);
  10312. },
  10313. "put test data for upload progress");
  10314. }
  10315. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10316. TestStringBodyUploadProgress(
  10317. [](Server &svr) {
  10318. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10319. res.set_content("patch received", "text/plain");
  10320. });
  10321. },
  10322. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10323. return cli.Patch("/test", body, "text/plain", progress_callback);
  10324. },
  10325. "patch test data for upload progress");
  10326. }
  10327. // Helper function for content provider upload progress tests
  10328. template <typename SetupHandler, typename ClientCall>
  10329. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10330. ClientCall &&client_call) {
  10331. Server svr;
  10332. setup_handler(svr);
  10333. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. });
  10338. svr.wait_until_ready();
  10339. Client cli(HOST, PORT);
  10340. vector<uint64_t> progress_values;
  10341. auto res =
  10342. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10343. progress_values.push_back(current);
  10344. return true;
  10345. });
  10346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10347. EXPECT_EQ(200, res->status);
  10348. EXPECT_FALSE(progress_values.empty());
  10349. }
  10350. TEST(UploadProgressTest, PostContentProviderProgress) {
  10351. TestContentProviderUploadProgress(
  10352. [](Server &svr) {
  10353. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10354. res.set_content("provider received", "text/plain");
  10355. });
  10356. },
  10357. [](Client &cli, UploadProgress progress_callback) {
  10358. return cli.Post(
  10359. "/test", 9,
  10360. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10361. sink.os << "test data";
  10362. return true;
  10363. },
  10364. "text/plain", progress_callback);
  10365. });
  10366. }
  10367. // Helper function for multipart upload progress tests
  10368. template <typename SetupHandler, typename ClientCall>
  10369. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10370. ClientCall &&client_call,
  10371. const string &endpoint) {
  10372. Server svr;
  10373. setup_handler(svr);
  10374. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10375. auto se = detail::scope_exit([&] {
  10376. svr.stop();
  10377. t.join();
  10378. });
  10379. svr.wait_until_ready();
  10380. Client cli(HOST, PORT);
  10381. vector<uint64_t> progress_values;
  10382. UploadFormDataItems items = {
  10383. {"field1", "value1", "", ""},
  10384. {"field2", "longer value for progress tracking test", "", ""},
  10385. {"file1", "file content data for upload progress", "test.txt",
  10386. "text/plain"}};
  10387. auto res = client_call(cli, endpoint, items,
  10388. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10389. progress_values.push_back(current);
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(200, res->status);
  10394. EXPECT_FALSE(progress_values.empty());
  10395. }
  10396. TEST(UploadProgressTest, PostMultipartProgress) {
  10397. TestMultipartUploadProgress(
  10398. [](Server &svr) {
  10399. svr.Post("/multipart", [](const Request &req, Response &res) {
  10400. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10401. res.set_content("multipart received", "text/plain");
  10402. });
  10403. },
  10404. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10405. UploadProgress progress_callback) {
  10406. return cli.Post(endpoint, items, progress_callback);
  10407. },
  10408. "/multipart");
  10409. }
  10410. // Helper function for basic download progress tests
  10411. template <typename SetupHandler, typename ClientCall>
  10412. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10413. ClientCall &&client_call, const string &endpoint,
  10414. size_t expected_content_size) {
  10415. Server svr;
  10416. setup_handler(svr);
  10417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10418. auto se = detail::scope_exit([&] {
  10419. svr.stop();
  10420. t.join();
  10421. });
  10422. svr.wait_until_ready();
  10423. Client cli(HOST, PORT);
  10424. vector<uint64_t> progress_values;
  10425. auto res = client_call(cli, endpoint,
  10426. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10427. progress_values.push_back(current);
  10428. return true;
  10429. });
  10430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10431. EXPECT_EQ(200, res->status);
  10432. EXPECT_FALSE(progress_values.empty());
  10433. EXPECT_EQ(expected_content_size, res->body.size());
  10434. }
  10435. TEST(DownloadProgressTest, GetBasic) {
  10436. TestBasicDownloadProgress(
  10437. [](Server &svr) {
  10438. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10439. string content(1000, 'D');
  10440. res.set_content(content, "text/plain");
  10441. });
  10442. },
  10443. [](Client &cli, const string &endpoint,
  10444. DownloadProgress progress_callback) {
  10445. return cli.Get(endpoint, progress_callback);
  10446. },
  10447. "/download", 1000u);
  10448. }
  10449. // Helper function for content receiver download progress tests
  10450. template <typename SetupHandler, typename ClientCall>
  10451. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10452. ClientCall &&client_call,
  10453. const string &endpoint,
  10454. size_t expected_content_size) {
  10455. Server svr;
  10456. setup_handler(svr);
  10457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10458. auto se = detail::scope_exit([&] {
  10459. svr.stop();
  10460. t.join();
  10461. });
  10462. svr.wait_until_ready();
  10463. Client cli(HOST, PORT);
  10464. vector<uint64_t> progress_values;
  10465. string received_body;
  10466. auto res = client_call(
  10467. cli, endpoint,
  10468. [&](const char *data, size_t data_length) -> bool {
  10469. received_body.append(data, data_length);
  10470. return true;
  10471. },
  10472. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10473. progress_values.push_back(current);
  10474. return true;
  10475. });
  10476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10477. EXPECT_EQ(200, res->status);
  10478. EXPECT_FALSE(progress_values.empty());
  10479. EXPECT_EQ(expected_content_size, received_body.size());
  10480. EXPECT_TRUE(res->body.empty());
  10481. }
  10482. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10483. TestContentReceiverDownloadProgress(
  10484. [](Server &svr) {
  10485. svr.Get("/download-receiver",
  10486. [](const Request & /*req*/, Response &res) {
  10487. string content(2000, 'R');
  10488. res.set_content(content, "text/plain");
  10489. });
  10490. },
  10491. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10492. DownloadProgress progress_callback) {
  10493. return cli.Get(endpoint, content_receiver, progress_callback);
  10494. },
  10495. "/download-receiver", 2000u);
  10496. }
  10497. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10498. // A provider reaching a pass with nothing to hand over - an empty buffer
  10499. // popped off a queue, say - must not be taken to mean the body is finished.
  10500. // It used to end the loop with the terminating chunk unwritten while the
  10501. // server still considered the response complete, so the peer waited for an
  10502. // end that never arrived.
  10503. Server svr;
  10504. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10505. auto step = std::make_shared<int>(0);
  10506. res.set_chunked_content_provider("text/plain",
  10507. [step](size_t /*offset*/, DataSink &sink) {
  10508. switch ((*step)++) {
  10509. case 0: sink.write("", 0); break;
  10510. case 1: sink.write("hello", 5); break;
  10511. default: sink.done(); break;
  10512. }
  10513. return true;
  10514. });
  10515. });
  10516. auto port = svr.bind_to_any_port(HOST);
  10517. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10518. auto listen_se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client cli(HOST, port);
  10525. // Without the fix the body is never terminated, so bound the wait rather
  10526. // than letting the test hang on the default read timeout.
  10527. cli.set_read_timeout(5, 0);
  10528. auto res = cli.Get("/stream");
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(StatusCode::OK_200, res->status);
  10531. EXPECT_EQ("hello", res->body);
  10532. }
  10533. TEST(StreamingTest, NoContentLengthStreaming) {
  10534. Server svr;
  10535. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10536. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10537. if (offset < 6) {
  10538. sink.os << (offset < 3 ? "a" : "b");
  10539. } else {
  10540. sink.done();
  10541. }
  10542. return true;
  10543. });
  10544. });
  10545. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10546. auto listen_se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. listen_thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client client(HOST, PORT);
  10553. auto get_thread = std::thread([&client]() {
  10554. std::string s;
  10555. auto res =
  10556. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10557. s += std::string(data, len);
  10558. return true;
  10559. });
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. EXPECT_EQ("aaabbb", s);
  10563. });
  10564. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10565. // Give GET time to get a few messages.
  10566. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10567. }
  10568. TEST(MountTest, Unmount) {
  10569. Server svr;
  10570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10571. auto se = detail::scope_exit([&] {
  10572. svr.stop();
  10573. listen_thread.join();
  10574. ASSERT_FALSE(svr.is_running());
  10575. });
  10576. svr.wait_until_ready();
  10577. Client cli("localhost", PORT);
  10578. svr.set_mount_point("/mount2", "./www2");
  10579. auto res = cli.Get("/");
  10580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10581. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10582. res = cli.Get("/mount2/dir/test.html");
  10583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10584. EXPECT_EQ(StatusCode::OK_200, res->status);
  10585. svr.set_mount_point("/", "./www");
  10586. res = cli.Get("/dir/");
  10587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10588. EXPECT_EQ(StatusCode::OK_200, res->status);
  10589. svr.remove_mount_point("/");
  10590. res = cli.Get("/dir/");
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10593. svr.remove_mount_point("/mount2");
  10594. res = cli.Get("/mount2/dir/test.html");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10597. }
  10598. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10599. Server svr;
  10600. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10601. svr.Get("/api/hello", [](const Request &, Response &res) {
  10602. res.set_content("api", "text/plain");
  10603. });
  10604. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10605. auto se = detail::scope_exit([&] {
  10606. svr.stop();
  10607. listen_thread.join();
  10608. ASSERT_FALSE(svr.is_running());
  10609. });
  10610. svr.wait_until_ready();
  10611. Client cli(HOST, PORT);
  10612. auto res = cli.Get("/dir/test.html");
  10613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10614. EXPECT_EQ(StatusCode::OK_200, res->status);
  10615. res = cli.Get("/api/hello");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::OK_200, res->status);
  10618. EXPECT_EQ("api", res->body);
  10619. }
  10620. TEST(MountTest, PathSegmentBoundary) {
  10621. Server svr;
  10622. svr.set_mount_point("/mount2", "./www2");
  10623. svr.set_mount_point("/", "./www");
  10624. auto port = svr.bind_to_any_port(HOST);
  10625. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.wait_until_ready();
  10632. Client cli(HOST, port);
  10633. auto res = cli.Get("/mount2/dir/test.html");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. // "/mount2" must not match part-way through a path segment.
  10637. res = cli.Get("/mount2dir/test.html");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10640. // A mount point ending in '/' keeps matching every path below it.
  10641. res = cli.Get("/dir/test.html");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MountTest, Redicect) {
  10646. Server svr;
  10647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. listen_thread.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.set_mount_point("/", "./www");
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. auto res = cli.Get("/dir/");
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. res = cli.Get("/dir");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10662. res = cli.Get("/file");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::OK_200, res->status);
  10665. res = cli.Get("/file/");
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10668. cli.set_follow_location(true);
  10669. res = cli.Get("/dir");
  10670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10671. EXPECT_EQ(StatusCode::OK_200, res->status);
  10672. }
  10673. TEST(MountTest, MultibytesPathName) {
  10674. Server svr;
  10675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.set_mount_point("/", "./www");
  10682. svr.wait_until_ready();
  10683. Client cli("localhost", PORT);
  10684. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::OK_200, res->status);
  10687. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10688. }
  10689. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10690. // in the pre-routing handler sees the path of every file that is served
  10691. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10692. Server svr;
  10693. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10694. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10695. if (req.path == "/dir/test.html") {
  10696. res.status = StatusCode::Unauthorized_401;
  10697. return Server::HandlerResponse::Handled;
  10698. }
  10699. return Server::HandlerResponse::Unhandled;
  10700. });
  10701. auto port = svr.bind_to_any_port(HOST);
  10702. ASSERT_LT(0, port);
  10703. thread t = thread([&] { svr.listen_after_bind(); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. t.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli(HOST, port);
  10711. for (auto path :
  10712. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10713. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10714. SCOPED_TRACE(path);
  10715. auto res = cli.Get(path);
  10716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10718. }
  10719. }
  10720. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10721. Server svr;
  10722. svr.set_mount_point("/", "./www");
  10723. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10724. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10725. auto port = svr.bind_to_any_port(HOST);
  10726. ASSERT_GT(port, 0);
  10727. thread t = thread([&] { svr.listen_after_bind(); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, port);
  10735. auto res = cli.Get("/dir/test.abcde");
  10736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10737. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10738. res = cli.Get("/dir/test.html");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10741. }
  10742. #ifdef _WIN32
  10743. // Issue #2435: mmap::open() must succeed even when another handle holds
  10744. // the file open for writing (e.g. an active log file).
  10745. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10746. const char *path = "mmap_concurrent_writer_test.txt";
  10747. const char *content = "hello";
  10748. {
  10749. std::ofstream f(path, std::ios::binary);
  10750. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10751. }
  10752. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10753. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10754. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10755. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10756. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10757. detail::mmap m(path);
  10758. ASSERT_TRUE(m.is_open());
  10759. EXPECT_EQ(strlen(content), m.size());
  10760. char buf[8];
  10761. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10762. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10763. }
  10764. #endif
  10765. #ifndef _WIN32
  10766. // A directory or a device has no size to serve.
  10767. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10768. const char *path = "./mmap_not_regular_test_dir";
  10769. ASSERT_EQ(0, ::mkdir(path, 0755));
  10770. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10771. for (auto p : {path, "/dev/null"}) {
  10772. detail::mmap m(p);
  10773. EXPECT_FALSE(m.is_open()) << p;
  10774. EXPECT_EQ(0U, m.size()) << p;
  10775. }
  10776. Server svr;
  10777. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10778. res.set_file_content("/dev/null");
  10779. });
  10780. auto port = svr.bind_to_any_port(HOST);
  10781. thread t = thread([&] { svr.listen_after_bind(); });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. t.join();
  10785. });
  10786. svr.wait_until_ready();
  10787. auto res = Client(HOST, port).Get("/null");
  10788. ASSERT_TRUE(res);
  10789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10790. }
  10791. #endif
  10792. #ifdef __linux__
  10793. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10794. TEST(MmapTest, FileIsNotMapped) {
  10795. const char *path = "mmap_not_mapped_test.txt";
  10796. {
  10797. std::ofstream f(path, std::ios::binary);
  10798. f << "hello";
  10799. }
  10800. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10801. detail::mmap m(path);
  10802. ASSERT_TRUE(m.is_open());
  10803. std::ifstream maps("/proc/self/maps");
  10804. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10805. std::istreambuf_iterator<char>());
  10806. EXPECT_EQ(std::string::npos, mappings.find(path));
  10807. }
  10808. #endif
  10809. TEST(KeepAliveTest, ReadTimeout) {
  10810. Server svr;
  10811. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10812. std::this_thread::sleep_for(std::chrono::seconds(2));
  10813. res.set_content("a", "text/plain");
  10814. });
  10815. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10816. res.set_content("b", "text/plain");
  10817. });
  10818. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10819. auto se = detail::scope_exit([&] {
  10820. svr.stop();
  10821. listen_thread.join();
  10822. ASSERT_FALSE(svr.is_running());
  10823. });
  10824. svr.wait_until_ready();
  10825. Client cli("localhost", PORT);
  10826. cli.set_keep_alive(true);
  10827. cli.set_read_timeout(std::chrono::seconds(1));
  10828. auto resa = cli.Get("/a");
  10829. ASSERT_FALSE(resa);
  10830. EXPECT_EQ(Error::Read, resa.error());
  10831. auto resb = cli.Get("/b");
  10832. ASSERT_TRUE(resb);
  10833. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10834. EXPECT_EQ("b", resb->body);
  10835. }
  10836. TEST(KeepAliveTest, MaxCount) {
  10837. size_t keep_alive_max_count = 3;
  10838. Server svr;
  10839. svr.set_keep_alive_max_count(keep_alive_max_count);
  10840. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10841. res.set_content("Hello World!", "text/plain");
  10842. });
  10843. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10844. auto se = detail::scope_exit([&] {
  10845. svr.stop();
  10846. listen_thread.join();
  10847. ASSERT_FALSE(svr.is_running());
  10848. });
  10849. svr.wait_until_ready();
  10850. Client cli(HOST, PORT);
  10851. cli.set_keep_alive(true);
  10852. for (size_t i = 0; i < 5; i++) {
  10853. auto result = cli.Get("/hi");
  10854. ASSERT_TRUE(result);
  10855. EXPECT_EQ(StatusCode::OK_200, result->status);
  10856. if (i == keep_alive_max_count - 1) {
  10857. EXPECT_EQ("close", result->get_header_value("Connection"));
  10858. } else {
  10859. EXPECT_FALSE(result->has_header("Connection"));
  10860. }
  10861. }
  10862. }
  10863. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10864. // can pull the next one into the server's buffer. The server must serve it
  10865. // without waiting for the socket to become readable again. The keep-alive
  10866. // timeout outlasts the client's read timeout, so a request left waiting for it
  10867. // shows up as a missing response.
  10868. static void serve_pipelining_routes(Server &svr,
  10869. const std::function<void(int)> &client) {
  10870. svr.set_keep_alive_timeout(5);
  10871. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10872. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10873. });
  10874. svr.Post("/echo", [](const Request &req, Response &res) {
  10875. res.set_content("echo " + req.body, "text/plain");
  10876. });
  10877. auto port = svr.bind_to_any_port(HOST);
  10878. thread t = thread([&] { svr.listen_after_bind(); });
  10879. auto se = detail::scope_exit([&] {
  10880. svr.stop();
  10881. t.join();
  10882. });
  10883. svr.wait_until_ready();
  10884. client(port);
  10885. }
  10886. static std::string
  10887. send_pipelined_requests(const std::vector<std::string> &parts) {
  10888. Server svr;
  10889. std::string res;
  10890. serve_pipelining_routes(svr, [&](int port) {
  10891. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10892. });
  10893. return res;
  10894. }
  10895. static void expect_in_order(const std::string &res,
  10896. const std::vector<std::string> &bodies) {
  10897. size_t pos = 0;
  10898. for (const auto &body : bodies) {
  10899. pos = res.find(body, pos);
  10900. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10901. pos += body.size();
  10902. }
  10903. }
  10904. TEST(KeepAliveTest, PipelinedRequests) {
  10905. auto res = send_pipelined_requests(
  10906. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10907. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10908. "Content-Length: 4\r\n\r\nbody"
  10909. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10910. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10911. }
  10912. // The second request starts in the server's buffer and ends on the socket.
  10913. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10914. auto res =
  10915. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10916. "GET /hi/2 HTTP/1.1\r\nHo",
  10917. "st: localhost\r\nConnection: close\r\n\r\n"});
  10918. expect_in_order(res, {"hi 1", "hi 2"});
  10919. }
  10920. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10921. // CRLF after a body does not turn into a 400 for the next request.
  10922. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10923. auto res = send_pipelined_requests(
  10924. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10925. "Content-Length: 4\r\n\r\nbody\r\n"
  10926. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10927. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10928. expect_in_order(res, {"echo body", "hi 2"});
  10929. }
  10930. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10931. // must not be served as the next request.
  10932. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10933. auto res = send_pipelined_requests(
  10934. {"INVALID REQUEST LINE\r\n\r\n"
  10935. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10936. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10937. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10938. }
  10939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10940. // Over TLS, the next request is held by the TLS library as already decrypted
  10941. // data rather than on the socket.
  10942. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10944. std::string res;
  10945. serve_pipelining_routes(svr, [&](int port) {
  10946. // One part, so all three requests arrive in one TLS record
  10947. EXPECT_TRUE(send_ssl_request_in_parts(
  10948. 2,
  10949. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10950. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10951. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10952. &res, port));
  10953. });
  10954. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10955. }
  10956. #endif
  10957. TEST(KeepAliveTest, Issue1041) {
  10958. Server svr;
  10959. svr.set_keep_alive_timeout(3);
  10960. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10961. res.set_content("Hello World!", "text/plain");
  10962. });
  10963. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. listen_thread.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. });
  10969. svr.wait_until_ready();
  10970. Client cli(HOST, PORT);
  10971. cli.set_keep_alive(true);
  10972. auto result = cli.Get("/hi");
  10973. ASSERT_TRUE(result);
  10974. EXPECT_EQ(StatusCode::OK_200, result->status);
  10975. std::this_thread::sleep_for(std::chrono::seconds(5));
  10976. result = cli.Get("/hi");
  10977. ASSERT_TRUE(result);
  10978. EXPECT_EQ(StatusCode::OK_200, result->status);
  10979. }
  10980. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10981. Server svr;
  10982. svr.set_keep_alive_max_count(0);
  10983. std::set<int> remote_ports;
  10984. svr.Get("/hi", [&](const Request &req, Response &res) {
  10985. remote_ports.insert(req.remote_port);
  10986. res.set_content("hi", "text/plain");
  10987. });
  10988. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. Client cli(HOST, PORT);
  10996. cli.set_keep_alive(true);
  10997. for (int i = 0; i < 3; i++) {
  10998. auto res = cli.Get("/hi");
  10999. ASSERT_TRUE(res);
  11000. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11001. }
  11002. // All three over one connection
  11003. EXPECT_EQ(1u, remote_ports.size());
  11004. }
  11005. TEST(KeepAliveTest, Issue1959) {
  11006. Server svr;
  11007. svr.set_keep_alive_timeout(5);
  11008. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11009. res.set_content("a", "text/plain");
  11010. });
  11011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11012. auto se = detail::scope_exit([&] {
  11013. if (!svr.is_running()) return;
  11014. svr.stop();
  11015. listen_thread.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. });
  11018. svr.wait_until_ready();
  11019. Client cli("localhost", PORT);
  11020. cli.set_keep_alive(true);
  11021. using namespace std::chrono;
  11022. auto start = steady_clock::now();
  11023. cli.Get("/a");
  11024. svr.stop();
  11025. listen_thread.join();
  11026. auto end = steady_clock::now();
  11027. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11028. EXPECT_LT(elapsed, 5000);
  11029. }
  11030. #ifdef CPPHTTPLIB_SSL_ENABLED
  11031. TEST(KeepAliveTest, SSLClientReconnection) {
  11032. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11033. ASSERT_TRUE(svr.is_valid());
  11034. svr.set_keep_alive_timeout(1);
  11035. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11036. res.set_content("Hello World!", "text/plain");
  11037. });
  11038. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11039. auto se = detail::scope_exit([&] {
  11040. svr.stop();
  11041. listen_thread.join();
  11042. ASSERT_FALSE(svr.is_running());
  11043. });
  11044. svr.wait_until_ready();
  11045. SSLClient cli(HOST, PORT);
  11046. cli.enable_server_certificate_verification(false);
  11047. cli.set_keep_alive(true);
  11048. auto result = cli.Get("/hi");
  11049. ASSERT_TRUE(result);
  11050. EXPECT_EQ(StatusCode::OK_200, result->status);
  11051. result = cli.Get("/hi");
  11052. ASSERT_TRUE(result);
  11053. EXPECT_EQ(StatusCode::OK_200, result->status);
  11054. std::this_thread::sleep_for(std::chrono::seconds(2));
  11055. // Recoonect
  11056. result = cli.Get("/hi");
  11057. ASSERT_TRUE(result);
  11058. EXPECT_EQ(StatusCode::OK_200, result->status);
  11059. result = cli.Get("/hi");
  11060. ASSERT_TRUE(result);
  11061. EXPECT_EQ(StatusCode::OK_200, result->status);
  11062. }
  11063. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.set_keep_alive_timeout(1);
  11067. std::string content = "reconnect";
  11068. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11069. res.set_content("Hello World!", "text/plain");
  11070. });
  11071. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. SSLClient cli(HOST, PORT);
  11079. cli.enable_server_certificate_verification(false);
  11080. cli.set_keep_alive(true);
  11081. auto result = cli.Post(
  11082. "/hi", content.size(),
  11083. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11084. sink.write(content.c_str(), content.size());
  11085. return true;
  11086. },
  11087. "text/plain");
  11088. ASSERT_TRUE(result);
  11089. EXPECT_EQ(200, result->status);
  11090. std::this_thread::sleep_for(std::chrono::seconds(2));
  11091. // Recoonect
  11092. result = cli.Post(
  11093. "/hi", content.size(),
  11094. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11095. sink.write(content.c_str(), content.size());
  11096. return true;
  11097. },
  11098. "text/plain");
  11099. ASSERT_TRUE(result);
  11100. EXPECT_EQ(200, result->status);
  11101. result = cli.Post(
  11102. "/hi", content.size(),
  11103. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11104. sink.write(content.c_str(), content.size());
  11105. return true;
  11106. },
  11107. "text/plain");
  11108. ASSERT_TRUE(result);
  11109. EXPECT_EQ(200, result->status);
  11110. }
  11111. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11112. using namespace httplib::tls;
  11113. {
  11114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11115. ASSERT_TRUE(svr.is_valid());
  11116. svr.Get("/sni", [&](const Request &req, Response &res) {
  11117. std::string expected = req.sni();
  11118. EXPECT_EQ(expected, req.get_param_value("expected"));
  11119. res.set_content("ok", "text/plain");
  11120. });
  11121. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11122. auto se = detail::scope_exit([&] {
  11123. svr.stop();
  11124. listen_thread.join();
  11125. ASSERT_FALSE(svr.is_running());
  11126. });
  11127. svr.wait_until_ready();
  11128. {
  11129. SSLClient cli("localhost", PORT);
  11130. cli.enable_server_certificate_verification(false);
  11131. auto res = cli.Get("/sni?expected=localhost");
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. }
  11134. {
  11135. SSLClient cli("::1", PORT);
  11136. cli.enable_server_certificate_verification(false);
  11137. auto res = cli.Get("/sni?expected=");
  11138. // NOTE: This may fail if the server is listening on IPv4 only
  11139. // (e.g., when localhost resolves to 127.0.0.1 only)
  11140. if (res) {
  11141. EXPECT_EQ(StatusCode::OK_200, res->status);
  11142. } else {
  11143. EXPECT_EQ(Error::Connection, res.error());
  11144. }
  11145. }
  11146. }
  11147. }
  11148. // The SNI of a failed handshake does not reach the next connection that the
  11149. // same worker thread serves
  11150. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11152. ASSERT_TRUE(svr.is_valid());
  11153. svr.new_task_queue = [] { return new ThreadPool(1); };
  11154. svr.Get("/sni", [](const Request &req, Response &res) {
  11155. res.set_content(req.sni(), "text/plain");
  11156. });
  11157. auto port = svr.bind_to_any_port("127.0.0.1");
  11158. ASSERT_LT(0, port);
  11159. thread t = thread([&] { svr.listen_after_bind(); });
  11160. auto se = detail::scope_exit([&] {
  11161. svr.stop();
  11162. t.join();
  11163. ASSERT_FALSE(svr.is_running());
  11164. });
  11165. svr.wait_until_ready();
  11166. {
  11167. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11168. SSLClient cli("localhost", port);
  11169. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11170. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11171. auto res = cli.Get("/sni");
  11172. ASSERT_FALSE(res);
  11173. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11174. }
  11175. // An IP host sends no SNI (RFC 6066)
  11176. SSLClient cli("127.0.0.1", port);
  11177. cli.enable_server_certificate_verification(false);
  11178. auto res = cli.Get("/sni");
  11179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11180. EXPECT_EQ("", res->body);
  11181. }
  11182. #endif
  11183. TEST(ClientProblemDetectionTest, ContentProvider) {
  11184. Server svr;
  11185. size_t content_length = 1024 * 1024;
  11186. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11187. res.set_content_provider(
  11188. content_length, "text/plain",
  11189. [&](size_t offset, size_t length, DataSink &sink) {
  11190. auto out_len = std::min(length, static_cast<size_t>(1024));
  11191. std::string out(out_len, '@');
  11192. sink.write(out.data(), out_len);
  11193. return offset < 4096;
  11194. },
  11195. [](bool success) { ASSERT_FALSE(success); });
  11196. });
  11197. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11198. res.set_content_provider(
  11199. 0, "text/plain",
  11200. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11201. EXPECT_TRUE(false);
  11202. return true;
  11203. },
  11204. [](bool success) { ASSERT_FALSE(success); });
  11205. });
  11206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11207. auto se = detail::scope_exit([&] {
  11208. svr.stop();
  11209. listen_thread.join();
  11210. ASSERT_FALSE(svr.is_running());
  11211. });
  11212. svr.wait_until_ready();
  11213. Client cli("localhost", PORT);
  11214. {
  11215. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11216. size_t /*data_length*/) { return false; });
  11217. ASSERT_FALSE(res);
  11218. }
  11219. {
  11220. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11221. size_t /*data_length*/) { return false; });
  11222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11223. }
  11224. }
  11225. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11226. // A provider that reports success without writing anything and without
  11227. // calling done() used to be handed the same offset and length again on every
  11228. // pass, so it spun for as long as the peer stayed connected.
  11229. Server svr;
  11230. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11231. res.set_content("ok", "text/plain");
  11232. });
  11233. auto port = svr.bind_to_any_port(HOST);
  11234. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11235. auto se = detail::scope_exit([&] {
  11236. svr.stop();
  11237. listen_thread.join();
  11238. ASSERT_FALSE(svr.is_running());
  11239. });
  11240. svr.wait_until_ready();
  11241. std::atomic<int> call_count{0};
  11242. Client cli(HOST, port);
  11243. auto res = cli.Post(
  11244. "/", 1024,
  11245. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11246. // Give up after enough passes to show the spin, so that losing the
  11247. // check below fails this test instead of hanging it.
  11248. return ++call_count < 100;
  11249. },
  11250. "text/plain");
  11251. ASSERT_FALSE(res);
  11252. EXPECT_EQ(Error::Write, res.error());
  11253. EXPECT_EQ(1, call_count.load());
  11254. }
  11255. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11256. // A writer only has to assign `write`. The other three used to be left as
  11257. // empty std::functions, so a provider calling one threw
  11258. // std::bad_function_call out of the thread running it and took the whole
  11259. // process down.
  11260. DataSink sink;
  11261. std::string written;
  11262. sink.write = [&](const char *data, size_t data_len) {
  11263. written.append(data, data_len);
  11264. return true;
  11265. };
  11266. EXPECT_TRUE(sink.is_writable());
  11267. sink.done();
  11268. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11269. EXPECT_TRUE(written.empty());
  11270. }
  11271. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11272. // A sink that cannot carry trailers still has to finish.
  11273. DataSink sink;
  11274. auto done_count = 0;
  11275. sink.done = [&]() { done_count++; };
  11276. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11277. EXPECT_EQ(1, done_count);
  11278. }
  11279. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11280. Server svr;
  11281. const std::string body(4096, 'x');
  11282. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11283. res.set_content_provider(body.size(), "text/plain",
  11284. [&](size_t offset, size_t length, DataSink &sink) {
  11285. sink.write(body.data() + offset, length);
  11286. sink.done();
  11287. return true;
  11288. });
  11289. });
  11290. auto port = svr.bind_to_any_port(HOST);
  11291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11292. auto se = detail::scope_exit([&] {
  11293. svr.stop();
  11294. listen_thread.join();
  11295. ASSERT_FALSE(svr.is_running());
  11296. });
  11297. svr.wait_until_ready();
  11298. Client cli(HOST, port);
  11299. auto res = cli.Get("/");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ(body, res->body);
  11303. }
  11304. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11305. Server svr;
  11306. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11307. res.set_content_provider(
  11308. 1024, "text/plain",
  11309. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11310. sink.write("hello", 5);
  11311. sink.done(); // short of the 1024 bytes the response promised
  11312. return true;
  11313. });
  11314. });
  11315. auto port = svr.bind_to_any_port(HOST);
  11316. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11317. auto se = detail::scope_exit([&] {
  11318. svr.stop();
  11319. listen_thread.join();
  11320. ASSERT_FALSE(svr.is_running());
  11321. });
  11322. svr.wait_until_ready();
  11323. Client cli(HOST, port);
  11324. cli.set_read_timeout(5, 0);
  11325. // The response is short of its Content-Length, so the client cannot read a
  11326. // complete body. What matters is that this returns at all: a no-op done()
  11327. // would leave the writer looping over a provider that never makes progress.
  11328. auto res = cli.Get("/");
  11329. EXPECT_FALSE(res);
  11330. }
  11331. // Read as the next response by a peer that sees it after a framed body.
  11332. static const std::string smuggled_response =
  11333. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11334. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11335. Server svr;
  11336. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11337. res.set_content_provider(
  11338. 5, "text/plain",
  11339. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11340. auto data = "AAAAA" + smuggled_response;
  11341. sink.write(data.data(), data.size());
  11342. return true;
  11343. });
  11344. });
  11345. thread t = thread([&] { svr.listen(HOST, PORT); });
  11346. auto se = detail::scope_exit([&] {
  11347. svr.stop();
  11348. t.join();
  11349. ASSERT_FALSE(svr.is_running());
  11350. });
  11351. svr.wait_until_ready();
  11352. std::string resp;
  11353. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11354. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11355. resp.clear();
  11356. ASSERT_TRUE(send_request(
  11357. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11358. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11359. }
  11360. TEST(NoContentTest, BodyIsNotSent) {
  11361. Server svr;
  11362. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11363. res.status = StatusCode::NoContent_204;
  11364. res.set_content(smuggled_response, "text/plain");
  11365. });
  11366. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11367. res.status = StatusCode::NotModified_304;
  11368. res.set_chunked_content_provider(
  11369. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11370. sink.write(smuggled_response.data(), smuggled_response.size());
  11371. sink.done();
  11372. return true;
  11373. });
  11374. });
  11375. thread t = thread([&] { svr.listen(HOST, PORT); });
  11376. auto se = detail::scope_exit([&] {
  11377. svr.stop();
  11378. t.join();
  11379. ASSERT_FALSE(svr.is_running());
  11380. });
  11381. svr.wait_until_ready();
  11382. for (auto path : {"/204", "/304"}) {
  11383. std::string resp;
  11384. ASSERT_TRUE(send_request(
  11385. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11386. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11387. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11388. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11389. }
  11390. }
  11391. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11392. Server svr;
  11393. std::atomic<bool> smuggled(false);
  11394. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11395. res.set_content("ok", "text/plain");
  11396. });
  11397. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11398. smuggled = true;
  11399. });
  11400. auto port = svr.bind_to_any_port(HOST);
  11401. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. // What follows the body would be read as the next request.
  11409. Client cli(HOST, port);
  11410. auto res = cli.Post(
  11411. "/", 5,
  11412. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11413. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11414. sink.write(data.data(), data.size());
  11415. return true;
  11416. },
  11417. "text/plain");
  11418. ASSERT_FALSE(res);
  11419. EXPECT_EQ(Error::Write, res.error());
  11420. EXPECT_FALSE(smuggled);
  11421. }
  11422. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11423. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11424. // The compressed path builds the whole body before connecting, so this
  11425. // fails client-side and never reaches a server.
  11426. Client cli(HOST, PORT);
  11427. cli.set_compress(true);
  11428. auto res = cli.Post(
  11429. "/", 1024,
  11430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11431. sink.write("hello", 5);
  11432. sink.done(); // short of the 1024 bytes the request announced
  11433. return true;
  11434. },
  11435. "text/plain");
  11436. ASSERT_FALSE(res);
  11437. EXPECT_EQ(Error::Write, res.error());
  11438. }
  11439. #endif
  11440. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11441. Server svr;
  11442. svr.set_error_handler([](Request const &, Response &res) -> void {
  11443. res.set_chunked_content_provider(
  11444. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11445. sink.os << "hello";
  11446. sink.os << "world";
  11447. sink.done();
  11448. return true;
  11449. });
  11450. });
  11451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11452. auto se = detail::scope_exit([&] {
  11453. svr.stop();
  11454. listen_thread.join();
  11455. ASSERT_FALSE(svr.is_running());
  11456. });
  11457. svr.wait_until_ready();
  11458. Client cli("localhost", PORT);
  11459. auto res = cli.Get("/");
  11460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11462. EXPECT_EQ("helloworld", res->body);
  11463. }
  11464. // A body set after a content provider must replace it, not be sent through it.
  11465. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11466. Server svr;
  11467. svr.set_mount_point("/", "./www");
  11468. svr.set_file_request_handler([](const Request &req, Response &res) {
  11469. if (req.path == "/dir/test.html") {
  11470. res.status = StatusCode::Forbidden_403;
  11471. res.set_content(std::string(5000, 'D'), "text/plain");
  11472. } else if (req.path == "/file") {
  11473. res.status = StatusCode::Forbidden_403;
  11474. res.body = "Denied";
  11475. }
  11476. });
  11477. auto port = svr.bind_to_any_port(HOST);
  11478. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11479. auto se = detail::scope_exit([&] {
  11480. svr.stop();
  11481. t.join();
  11482. ASSERT_FALSE(svr.is_running());
  11483. });
  11484. svr.wait_until_ready();
  11485. Client cli(HOST, port);
  11486. {
  11487. auto res = cli.Get("/dir/test.html");
  11488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11490. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11491. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11492. }
  11493. {
  11494. auto res = cli.Get("/file");
  11495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11496. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11497. EXPECT_EQ("Denied", res->body);
  11498. }
  11499. {
  11500. auto res = cli.Get("/dir/index.html");
  11501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11502. EXPECT_EQ(StatusCode::OK_200, res->status);
  11503. EXPECT_EQ(0U, res->body.find("<html>"));
  11504. }
  11505. }
  11506. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11507. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11508. Server svr;
  11509. std::vector<bool> released;
  11510. std::mutex released_mutex;
  11511. auto releaser = [&](bool success) {
  11512. std::lock_guard<std::mutex> guard(released_mutex);
  11513. released.push_back(success);
  11514. };
  11515. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11516. return sink.write(&"hello"[offset], length);
  11517. };
  11518. svr.Get("/sized", [&](const Request &, Response &res) {
  11519. res.status = StatusCode::NotFound_404;
  11520. res.set_content_provider(5, "text/plain", provider, releaser);
  11521. });
  11522. svr.Get("/chunked", [&](const Request &, Response &res) {
  11523. res.status = StatusCode::ServiceUnavailable_503;
  11524. res.set_chunked_content_provider(
  11525. "text/plain",
  11526. [](size_t, DataSink &sink) {
  11527. sink.os << "chunk";
  11528. sink.done();
  11529. return true;
  11530. },
  11531. releaser);
  11532. });
  11533. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11534. res.set_content_provider(5, "text/plain", provider, releaser);
  11535. throw std::runtime_error("after the provider");
  11536. });
  11537. svr.set_error_handler([](const Request &req, Response &res) {
  11538. // Leave the exception handler's content to it.
  11539. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11540. res.set_content(std::string(1000, 'E'), "text/html");
  11541. return Server::HandlerResponse::Handled;
  11542. });
  11543. svr.set_exception_handler(
  11544. [](const Request &, Response &res, std::exception_ptr) {
  11545. res.status = StatusCode::InternalServerError_500;
  11546. res.set_content(std::string(1000, 'X'), "text/html");
  11547. });
  11548. auto port = svr.bind_to_any_port(HOST);
  11549. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11550. auto se = detail::scope_exit([&] {
  11551. svr.stop();
  11552. t.join();
  11553. ASSERT_FALSE(svr.is_running());
  11554. });
  11555. svr.wait_until_ready();
  11556. Client cli(HOST, port);
  11557. {
  11558. auto res = cli.Get("/sized");
  11559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11561. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11562. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11563. }
  11564. {
  11565. auto res = cli.Get("/chunked");
  11566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11567. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11568. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11569. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11570. }
  11571. {
  11572. auto res = cli.Get("/throw");
  11573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11574. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11575. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11576. }
  11577. std::lock_guard<std::mutex> guard(released_mutex);
  11578. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11579. }
  11580. #endif
  11581. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11582. Server svr;
  11583. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11584. return sink.write(&"abc"[offset], length);
  11585. };
  11586. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11587. res.set_file_content("./www/dir/test.html");
  11588. res.set_content("body", "text/plain");
  11589. });
  11590. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11591. res.set_content(std::string(100, 'B'), "text/plain");
  11592. res.set_file_content("./www/dir/test.html");
  11593. });
  11594. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11595. res.set_content(std::string(100, 'B'), "text/plain");
  11596. res.set_content_provider(3, "text/x-provider", abc);
  11597. });
  11598. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11599. res.set_content_provider(3, "text/x-provider", abc);
  11600. res.set_content(std::string(100, 'B'), "text/plain");
  11601. });
  11602. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11603. res.set_content_provider(3, "text/x-provider", abc);
  11604. res.set_file_content("./www/dir/test.html", "text/x-file");
  11605. });
  11606. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11607. res.set_file_content("./www/dir/test.html");
  11608. res.set_header("Content-Type", "text/x-handler");
  11609. });
  11610. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11611. res.set_content_provider(3, "text/plain", abc);
  11612. res.body = "direct";
  11613. });
  11614. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11615. res.set_file_content("./www/dir/test.html");
  11616. res.body = "direct";
  11617. });
  11618. auto port = svr.bind_to_any_port(HOST);
  11619. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. t.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. Client cli(HOST, port);
  11627. auto expect_body = [&](const char *path, const std::string &body,
  11628. const std::string &type) {
  11629. // Uncompressed, so Content-Length can be compared with the body.
  11630. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11631. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11632. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11633. EXPECT_EQ(body, res->body) << path;
  11634. EXPECT_EQ(std::to_string(body.size()),
  11635. res->get_header_value("Content-Length"))
  11636. << path;
  11637. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11638. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11639. };
  11640. expect_body("/file-then-body", "body", "text/plain");
  11641. expect_body("/body-then-file", "test.html", "text/html");
  11642. expect_body("/body-then-provider", "abc", "text/x-provider");
  11643. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11644. expect_body("/provider-then-file", "test.html", "text/x-file");
  11645. expect_body("/file-then-header", "test.html", "text/x-handler");
  11646. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11647. expect_body("/file-then-direct-body", "direct", "text/plain");
  11648. // Ranges are checked against the body, not the dropped provider.
  11649. {
  11650. auto res = cli.Get("/provider-then-direct-body",
  11651. Headers{{make_range_header({{1, 2}})}});
  11652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11653. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11654. EXPECT_EQ("ir", res->body);
  11655. }
  11656. {
  11657. auto res = cli.Get("/file-then-direct-body",
  11658. Headers{{make_range_header({{7, 8}})}});
  11659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11660. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11661. }
  11662. }
  11663. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11664. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11665. const char *path = "./truncated_while_served.txt";
  11666. const size_t size = 32 * 1024 * 1024;
  11667. {
  11668. std::ofstream f(path, std::ios::binary);
  11669. f << std::string(size, 'x');
  11670. }
  11671. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11672. // Over TLS, where the bytes are encrypted in this process rather than
  11673. // copied by send().
  11674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11675. svr.Get("/file", [&](const Request &, Response &res) {
  11676. res.set_file_content(path, "text/plain");
  11677. });
  11678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. thread.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. // The file shrinks once the first bytes are in, as a rewrite in place
  11686. // would, and reading the mapping past its new end used to raise SIGBUS.
  11687. SSLClient cli(HOST, PORT);
  11688. cli.enable_server_certificate_verification(false);
  11689. size_t received = 0;
  11690. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11691. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11692. received += len;
  11693. return true;
  11694. });
  11695. EXPECT_FALSE(res);
  11696. EXPECT_LT(received, size);
  11697. }
  11698. #endif
  11699. // Forward declaration (see the base64_encode note).
  11700. namespace httplib {
  11701. namespace detail {
  11702. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11703. const std::string &content_type,
  11704. EncodingType encoding);
  11705. } // namespace detail
  11706. } // namespace httplib
  11707. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11708. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11709. ASSERT_TRUE(mm->is_open());
  11710. Response res;
  11711. detail::set_file_content_provider(res, mm, "text/html",
  11712. detail::EncodingType::None);
  11713. std::string out;
  11714. DataSink sink;
  11715. sink.write = [&](const char *d, size_t l) {
  11716. out.append(d, l);
  11717. return true;
  11718. };
  11719. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11720. EXPECT_EQ("test.html", out);
  11721. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11722. EXPECT_EQ("test.html", out);
  11723. }
  11724. TEST(LongPollingTest, ClientCloseDetection) {
  11725. Server svr;
  11726. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11727. res.set_chunked_content_provider(
  11728. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11729. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11730. sink.os << "hello";
  11731. auto count = 10;
  11732. while (count > 0 && sink.is_writable()) {
  11733. this_thread::sleep_for(chrono::milliseconds(10));
  11734. count--;
  11735. }
  11736. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11737. return true;
  11738. });
  11739. });
  11740. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11741. auto se = detail::scope_exit([&] {
  11742. svr.stop();
  11743. listen_thread.join();
  11744. ASSERT_FALSE(svr.is_running());
  11745. });
  11746. svr.wait_until_ready();
  11747. Client cli("localhost", PORT);
  11748. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11749. EXPECT_EQ("hello", string(data, data_length));
  11750. return false; // close the socket immediately.
  11751. });
  11752. ASSERT_FALSE(res);
  11753. }
  11754. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11755. Server svr;
  11756. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11757. res.set_chunked_content_provider(
  11758. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11759. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11760. sink.os << "hello";
  11761. EXPECT_TRUE(sink.os.good());
  11762. // Wait for the client to close the connection
  11763. auto count = 10;
  11764. while (count > 0 && sink.is_writable()) {
  11765. this_thread::sleep_for(chrono::milliseconds(10));
  11766. count--;
  11767. }
  11768. // After client disconnect, write repeatedly until the socket
  11769. // write actually fails (small writes may be absorbed by the
  11770. // kernel buffer)
  11771. std::string chunk(1024, 'x');
  11772. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11773. sink.os << chunk;
  11774. }
  11775. EXPECT_TRUE(sink.os.fail());
  11776. return true;
  11777. });
  11778. });
  11779. auto port = svr.bind_to_any_port("localhost");
  11780. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. listen_thread.join();
  11784. ASSERT_FALSE(svr.is_running());
  11785. });
  11786. svr.wait_until_ready();
  11787. Client cli("localhost", port);
  11788. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11789. EXPECT_EQ("hello", string(data, data_length));
  11790. return false; // close the socket immediately.
  11791. });
  11792. ASSERT_FALSE(res);
  11793. }
  11794. TEST(GetWithParametersTest, GetWithParameters) {
  11795. Server svr;
  11796. svr.Get("/", [&](const Request &req, Response &) {
  11797. EXPECT_EQ("world", req.get_param_value("hello"));
  11798. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11799. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11800. });
  11801. svr.Get("/params", [&](const Request &req, Response &) {
  11802. EXPECT_EQ("world", req.get_param_value("hello"));
  11803. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11804. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11805. });
  11806. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11807. EXPECT_EQ("resource-id", req.matches[1]);
  11808. EXPECT_EQ("foo", req.get_param_value("param1"));
  11809. EXPECT_EQ("bar", req.get_param_value("param2"));
  11810. });
  11811. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11812. EXPECT_EQ("user-id", req.path_params.at("id"));
  11813. EXPECT_EQ("foo", req.get_param_value("param1"));
  11814. EXPECT_EQ("bar", req.get_param_value("param2"));
  11815. });
  11816. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11817. auto se = detail::scope_exit([&] {
  11818. svr.stop();
  11819. listen_thread.join();
  11820. ASSERT_FALSE(svr.is_running());
  11821. });
  11822. svr.wait_until_ready();
  11823. {
  11824. Client cli(HOST, PORT);
  11825. Params params;
  11826. params.emplace("hello", "world");
  11827. params.emplace("hello2", "world2");
  11828. params.emplace("hello3", "world3");
  11829. auto res = cli.Get("/", params, Headers{});
  11830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11831. EXPECT_EQ(StatusCode::OK_200, res->status);
  11832. }
  11833. {
  11834. Client cli(HOST, PORT);
  11835. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. EXPECT_EQ(StatusCode::OK_200, res->status);
  11838. }
  11839. {
  11840. Client cli(HOST, PORT);
  11841. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ(StatusCode::OK_200, res->status);
  11844. }
  11845. {
  11846. Client cli(HOST, PORT);
  11847. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. }
  11851. }
  11852. TEST(GetWithParametersTest, GetWithParameters2) {
  11853. Server svr;
  11854. svr.Get("/", [&](const Request &req, Response &res) {
  11855. auto text = req.get_param_value("hello");
  11856. res.set_content(text, "text/plain");
  11857. });
  11858. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11859. auto se = detail::scope_exit([&] {
  11860. svr.stop();
  11861. listen_thread.join();
  11862. ASSERT_FALSE(svr.is_running());
  11863. });
  11864. svr.wait_until_ready();
  11865. Client cli("localhost", PORT);
  11866. Params params;
  11867. params.emplace("hello", "world");
  11868. std::string body;
  11869. auto res = cli.Get("/", params, Headers{},
  11870. [&](const char *data, size_t data_length) {
  11871. body.append(data, data_length);
  11872. return true;
  11873. });
  11874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11875. EXPECT_EQ(StatusCode::OK_200, res->status);
  11876. EXPECT_EQ("world", body);
  11877. }
  11878. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11879. Server svr;
  11880. svr.Get("/search", [&](const Request &req, Response &res) {
  11881. auto q = req.get_param_value("q");
  11882. res.set_content(q, "text/plain");
  11883. });
  11884. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11885. auto se = detail::scope_exit([&] {
  11886. svr.stop();
  11887. listen_thread.join();
  11888. ASSERT_FALSE(svr.is_running());
  11889. });
  11890. svr.wait_until_ready();
  11891. Client cli("localhost", PORT);
  11892. // Verify that Get(path, params) works without requiring Headers argument
  11893. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11895. EXPECT_EQ(StatusCode::OK_200, res->status);
  11896. EXPECT_EQ("cpp-httplib", res->body);
  11897. }
  11898. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11899. auto host = "httpbingo.org";
  11900. auto path = std::string{"/range/32"};
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli(host);
  11903. #else
  11904. Client cli(host);
  11905. #endif
  11906. cli.set_default_headers({make_range_header({{1, 10}})});
  11907. cli.set_connection_timeout(5);
  11908. {
  11909. auto res = cli.Get(path);
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ("bcdefghijk", res->body);
  11912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11913. }
  11914. {
  11915. auto res = cli.Get(path);
  11916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11917. EXPECT_EQ("bcdefghijk", res->body);
  11918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11919. }
  11920. }
  11921. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11922. Server svr;
  11923. svr.set_default_headers({{"Hello", "World"}});
  11924. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11925. res.set_content("ok", "text/plain");
  11926. });
  11927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. listen_thread.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. Client cli("localhost", PORT);
  11935. auto res = cli.Get("/");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. EXPECT_EQ(StatusCode::OK_200, res->status);
  11938. EXPECT_EQ("ok", res->body);
  11939. EXPECT_EQ("World", res->get_header_value("Hello"));
  11940. }
  11941. #ifdef CPPHTTPLIB_SSL_ENABLED
  11942. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11944. ASSERT_TRUE(svr.is_valid());
  11945. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11946. std::this_thread::sleep_for(std::chrono::seconds(2));
  11947. res.set_content("a", "text/plain");
  11948. });
  11949. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11950. res.set_content("b", "text/plain");
  11951. });
  11952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. listen_thread.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. SSLClient cli("localhost", PORT);
  11960. cli.enable_server_certificate_verification(false);
  11961. cli.set_keep_alive(true);
  11962. cli.set_read_timeout(std::chrono::seconds(1));
  11963. auto resa = cli.Get("/a");
  11964. ASSERT_TRUE(!resa);
  11965. EXPECT_EQ(Error::Read, resa.error());
  11966. auto resb = cli.Get("/b");
  11967. ASSERT_TRUE(resb);
  11968. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11969. EXPECT_EQ("b", resb->body);
  11970. }
  11971. // Closing an idle keep-alive connection sends close_notify and returns. The
  11972. // server must not wait for the client's close_notify: an idle client never
  11973. // sends one, so the worker would be held until the read timeout expires, and
  11974. // stop() would wait for it.
  11975. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11977. ASSERT_TRUE(svr.is_valid());
  11978. svr.set_keep_alive_timeout(1);
  11979. svr.set_read_timeout(10, 0);
  11980. svr.Get("/", [](const Request &, Response &res) {
  11981. res.set_content("ok", "text/plain");
  11982. });
  11983. auto port = svr.bind_to_any_port(HOST);
  11984. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11985. auto se = detail::scope_exit([&] {
  11986. if (listen_thread.joinable()) {
  11987. svr.stop();
  11988. listen_thread.join();
  11989. }
  11990. });
  11991. svr.wait_until_ready();
  11992. SSLClient cli(HOST, port);
  11993. cli.enable_server_certificate_verification(false);
  11994. cli.set_keep_alive(true);
  11995. auto res = cli.Get("/");
  11996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11997. EXPECT_EQ(StatusCode::OK_200, res->status);
  11998. // Stay idle past the keep-alive timeout so the server closes the connection.
  11999. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12000. auto start = std::chrono::steady_clock::now();
  12001. svr.stop();
  12002. listen_thread.join();
  12003. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12004. std::chrono::steady_clock::now() - start)
  12005. .count();
  12006. EXPECT_LT(elapsed, 3000);
  12007. }
  12008. #endif
  12009. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12010. protected:
  12011. ServerTestWithAI_PASSIVE()
  12012. : cli_(HOST, PORT)
  12013. #ifdef CPPHTTPLIB_SSL_ENABLED
  12014. ,
  12015. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12016. #endif
  12017. {
  12018. #ifdef CPPHTTPLIB_SSL_ENABLED
  12019. cli_.enable_server_certificate_verification(false);
  12020. #endif
  12021. }
  12022. virtual void SetUp() {
  12023. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12024. res.set_content("Hello World!", "text/plain");
  12025. });
  12026. t_ = thread(
  12027. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12028. svr_.wait_until_ready();
  12029. }
  12030. virtual void TearDown() {
  12031. svr_.stop();
  12032. t_.join();
  12033. }
  12034. #ifdef CPPHTTPLIB_SSL_ENABLED
  12035. SSLClient cli_;
  12036. SSLServer svr_;
  12037. #else
  12038. Client cli_;
  12039. Server svr_;
  12040. #endif
  12041. thread t_;
  12042. };
  12043. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12044. auto res = cli_.Get("/hi");
  12045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12046. EXPECT_EQ(StatusCode::OK_200, res->status);
  12047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12048. EXPECT_EQ("Hello World!", res->body);
  12049. }
  12050. class ServerUpDownTest : public ::testing::Test {
  12051. protected:
  12052. ServerUpDownTest() : cli_(HOST, PORT) {}
  12053. virtual void SetUp() {
  12054. t_ = thread([&]() {
  12055. svr_.bind_to_any_port(HOST);
  12056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12057. ASSERT_TRUE(svr_.listen_after_bind());
  12058. });
  12059. svr_.wait_until_ready();
  12060. }
  12061. virtual void TearDown() {
  12062. svr_.stop();
  12063. t_.join();
  12064. }
  12065. Client cli_;
  12066. Server svr_;
  12067. thread t_;
  12068. };
  12069. TEST_F(ServerUpDownTest, QuickStartStop) {
  12070. // Should not crash, especially when run with
  12071. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12072. }
  12073. class PayloadMaxLengthTest : public ::testing::Test {
  12074. protected:
  12075. PayloadMaxLengthTest()
  12076. : cli_(HOST, PORT)
  12077. #ifdef CPPHTTPLIB_SSL_ENABLED
  12078. ,
  12079. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12080. #endif
  12081. {
  12082. #ifdef CPPHTTPLIB_SSL_ENABLED
  12083. cli_.enable_server_certificate_verification(false);
  12084. #endif
  12085. }
  12086. virtual void SetUp() {
  12087. svr_.set_payload_max_length(8);
  12088. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12089. res.set_content("test", "text/plain");
  12090. });
  12091. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12092. svr_.wait_until_ready();
  12093. }
  12094. virtual void TearDown() {
  12095. svr_.stop();
  12096. t_.join();
  12097. }
  12098. #ifdef CPPHTTPLIB_SSL_ENABLED
  12099. SSLClient cli_;
  12100. SSLServer svr_;
  12101. #else
  12102. Client cli_;
  12103. Server svr_;
  12104. #endif
  12105. thread t_;
  12106. };
  12107. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12108. auto res = cli_.Post("/test", "123456789", "text/plain");
  12109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12110. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12111. res = cli_.Post("/test", "12345678", "text/plain");
  12112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12113. EXPECT_EQ(StatusCode::OK_200, res->status);
  12114. }
  12115. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12116. // Test chunked encoding with payload exceeding the 8-byte limit
  12117. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12118. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12120. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12121. }
  12122. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12123. // Test chunked encoding with payload within the 8-byte limit
  12124. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12125. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12127. EXPECT_EQ(StatusCode::OK_200, res->status);
  12128. }
  12129. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12130. // Test using send_request to send chunked data exceeding payload limit
  12131. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12132. "Host: " +
  12133. std::string(HOST) + ":" + std::to_string(PORT) +
  12134. "\r\n"
  12135. "Transfer-Encoding: chunked\r\n"
  12136. "Connection: close\r\n"
  12137. "\r\n"
  12138. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12139. "0123456789\r\n"
  12140. "0\r\n" // End chunk
  12141. "\r\n";
  12142. std::string response;
  12143. bool result = send_request(1, chunked_request, &response);
  12144. if (!result) {
  12145. // If send_request fails, it might be because the server closed the
  12146. // connection due to payload limit enforcement, which is acceptable
  12147. SUCCEED()
  12148. << "Server rejected oversized chunked request (connection closed)";
  12149. } else {
  12150. // If we got a response, check if it's an error response or connection was
  12151. // closed early Short response length indicates connection was closed due to
  12152. // payload limit
  12153. if (response.length() <= 10) {
  12154. SUCCEED() << "Server closed connection for oversized chunked request";
  12155. } else {
  12156. // Check for error status codes
  12157. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12158. response.find("Payload Too Large") != std::string::npos ||
  12159. response.find("400") != std::string::npos);
  12160. }
  12161. }
  12162. }
  12163. class LargePayloadMaxLengthTest : public ::testing::Test {
  12164. protected:
  12165. LargePayloadMaxLengthTest()
  12166. : cli_(HOST, PORT)
  12167. #ifdef CPPHTTPLIB_SSL_ENABLED
  12168. ,
  12169. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12170. #endif
  12171. {
  12172. #ifdef CPPHTTPLIB_SSL_ENABLED
  12173. cli_.enable_server_certificate_verification(false);
  12174. #endif
  12175. }
  12176. virtual void SetUp() {
  12177. // Set 10MB payload limit
  12178. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12179. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12180. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12181. res.set_content("Large payload test", "text/plain");
  12182. });
  12183. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12184. svr_.wait_until_ready();
  12185. }
  12186. virtual void TearDown() {
  12187. svr_.stop();
  12188. t_.join();
  12189. }
  12190. #ifdef CPPHTTPLIB_SSL_ENABLED
  12191. SSLClient cli_;
  12192. SSLServer svr_;
  12193. #else
  12194. Client cli_;
  12195. Server svr_;
  12196. #endif
  12197. thread t_;
  12198. };
  12199. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12200. // Test chunked encoding with payload within 10MB limit
  12201. std::string medium_payload(5 * 1024 * 1024,
  12202. 'A'); // 5MB payload, within 10MB limit
  12203. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. EXPECT_EQ(StatusCode::OK_200, res->status);
  12206. }
  12207. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12208. // Test chunked encoding with payload exceeding 10MB limit
  12209. std::string large_payload(12 * 1024 * 1024,
  12210. 'B'); // 12MB payload, exceeds 10MB limit
  12211. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12212. // Server may either return 413 or close the connection
  12213. if (res) {
  12214. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12215. } else {
  12216. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12217. }
  12218. }
  12219. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12220. Server svr;
  12221. svr.Get("/", [](const Request &, Response &res) {
  12222. // Claims the most the client accepts, far more than it sends, then drops
  12223. // the connection.
  12224. res.set_content_provider(std::string().max_size(), "text/plain",
  12225. [](size_t, size_t, DataSink &sink) {
  12226. sink.write("abc", 3);
  12227. return false;
  12228. });
  12229. });
  12230. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12231. auto se = detail::scope_exit([&] {
  12232. svr.stop();
  12233. thread.join();
  12234. ASSERT_FALSE(svr.is_running());
  12235. });
  12236. svr.wait_until_ready();
  12237. Client cli(HOST, PORT);
  12238. cli.set_payload_max_length(0);
  12239. EXPECT_FALSE(cli.Get("/"));
  12240. }
  12241. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12242. // Stream API does, not as a plain read failure
  12243. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12244. Server svr;
  12245. svr.Get("/big", [](const Request &, Response &res) {
  12246. res.set_content(std::string(100000, 'b'), "text/plain");
  12247. });
  12248. auto port = svr.bind_to_any_port(HOST);
  12249. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12250. auto se = detail::scope_exit([&] {
  12251. svr.stop();
  12252. thread.join();
  12253. });
  12254. svr.wait_until_ready();
  12255. Client cli(HOST, port);
  12256. cli.set_payload_max_length(1000);
  12257. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12258. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12259. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12260. [](const char *, size_t) { return true; });
  12261. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12263. // Small on the wire, over the limit once decompressed
  12264. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12265. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12266. #endif
  12267. }
  12268. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12269. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12270. // path.
  12271. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12272. Server svr;
  12273. const size_t LIMIT = 64 * 1024; // 64KB
  12274. svr.set_payload_max_length(LIMIT);
  12275. size_t total = 0;
  12276. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12277. const ContentReader &content_reader) {
  12278. content_reader([&](const char * /*data*/, size_t len) {
  12279. total += len;
  12280. return true;
  12281. });
  12282. res.status = 200;
  12283. res.set_content("stream_ok", "text/plain");
  12284. });
  12285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12286. auto se = detail::scope_exit([&] {
  12287. svr.stop();
  12288. thread.join();
  12289. ASSERT_FALSE(svr.is_running());
  12290. });
  12291. svr.wait_until_ready();
  12292. // Prepare 256KB raw data and gzip-compress it
  12293. std::string raw(256 * 1024, 'A');
  12294. std::string gz;
  12295. {
  12296. z_stream zs{};
  12297. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12298. Z_DEFAULT_STRATEGY);
  12299. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12300. zs.avail_in = static_cast<uInt>(raw.size());
  12301. char outbuf[4096];
  12302. int ret;
  12303. do {
  12304. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12305. zs.avail_out = sizeof(outbuf);
  12306. ret = deflate(&zs, Z_FINISH);
  12307. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12308. } while (ret != Z_STREAM_END);
  12309. deflateEnd(&zs);
  12310. }
  12311. Client cli(HOST, PORT);
  12312. cli.set_connection_timeout(std::chrono::seconds(5));
  12313. Headers headers = {{"Content-Encoding", "gzip"}};
  12314. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12315. "application/octet-stream");
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. // Server must reject oversized decompressed payloads with 413.
  12318. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12319. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12320. EXPECT_LE(total, LIMIT);
  12321. }
  12322. #endif
  12323. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12324. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12325. // the payload must be passed through untouched instead of being rejected.
  12326. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12327. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12328. Server svr;
  12329. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12330. res.set_content(body, "image/jpeg");
  12331. res.set_header("Content-Encoding", "UTF-8");
  12332. });
  12333. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12334. res.set_content(body, "image/jpeg");
  12335. res.set_header("Content-Encoding", "identity");
  12336. });
  12337. svr.Post("/echo", [](const Request &req, Response &res) {
  12338. res.set_content(req.body, "image/jpeg");
  12339. });
  12340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12341. auto se = detail::scope_exit([&] {
  12342. svr.stop();
  12343. t.join();
  12344. ASSERT_FALSE(svr.is_running());
  12345. });
  12346. svr.wait_until_ready();
  12347. Client cli(HOST, PORT);
  12348. {
  12349. auto res = cli.Get("/image");
  12350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12351. EXPECT_EQ(StatusCode::OK_200, res->status);
  12352. EXPECT_EQ(body, res->body);
  12353. }
  12354. {
  12355. auto res = cli.Get("/identity");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. EXPECT_EQ(StatusCode::OK_200, res->status);
  12358. EXPECT_EQ(body, res->body);
  12359. }
  12360. {
  12361. // The same applies to a request body reaching the server.
  12362. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12363. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::OK_200, res->status);
  12366. EXPECT_EQ(body, res->body);
  12367. }
  12368. }
  12369. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12370. // gzip-encoded response even when the build has no zlib support.
  12371. static const char GZIPPED_HELLO_WORLD[] = {
  12372. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12373. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12374. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12375. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12376. // A content coding is a whole token, not something the field value merely
  12377. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12378. // as "fibre" look like Brotli, and turned a multi-coding value like
  12379. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12380. // it was never meant to see.
  12381. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12382. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12383. Server svr;
  12384. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12385. res.set_content(body, "image/jpeg");
  12386. res.set_header("Content-Encoding", "fibre");
  12387. });
  12388. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12389. res.set_content(body, "image/jpeg");
  12390. res.set_header("Content-Encoding", "gzip, br");
  12391. });
  12392. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(body, "image/jpeg");
  12394. res.set_header("Content-Encoding", "x-zstd-ish");
  12395. });
  12396. auto port = svr.bind_to_any_port(HOST);
  12397. thread t = thread([&]() { svr.listen_after_bind(); });
  12398. auto se = detail::scope_exit([&] {
  12399. svr.stop();
  12400. t.join();
  12401. ASSERT_FALSE(svr.is_running());
  12402. });
  12403. svr.wait_until_ready();
  12404. Client cli(HOST, port);
  12405. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12406. auto res = cli.Get(path);
  12407. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12408. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12409. // Not a coding we recognize, so the payload comes back untouched
  12410. EXPECT_EQ(body, res->body) << path;
  12411. }
  12412. }
  12413. // A content coding cpp-httplib recognizes but was not built with must be
  12414. // reported as such. Handing the still-compressed payload back to the caller
  12415. // would silently corrupt it.
  12416. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12417. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12418. Server svr;
  12419. // "image/jpeg" keeps the server from applying a content coding of its own,
  12420. // so the hand-crafted Content-Encoding below survives.
  12421. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12422. res.set_content(gzipped, "image/jpeg");
  12423. res.set_header("Content-Encoding", "gzip");
  12424. });
  12425. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12426. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12427. res.set_content(gzipped, "image/jpeg");
  12428. res.set_header("Content-Encoding", "GZIP");
  12429. });
  12430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12431. auto se = detail::scope_exit([&] {
  12432. svr.stop();
  12433. t.join();
  12434. ASSERT_FALSE(svr.is_running());
  12435. });
  12436. svr.wait_until_ready();
  12437. Client cli(HOST, PORT);
  12438. {
  12439. auto res = cli.Get("/gzipped");
  12440. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12442. EXPECT_EQ("Hello World!", res->body);
  12443. #else
  12444. ASSERT_FALSE(res);
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12446. #endif
  12447. }
  12448. {
  12449. // open_stream() must behave the same way.
  12450. auto handle = cli.open_stream("GET", "/gzipped");
  12451. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12452. ASSERT_TRUE(handle.is_valid());
  12453. std::string received;
  12454. char buf[256];
  12455. ssize_t n;
  12456. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12457. received.append(buf, static_cast<size_t>(n));
  12458. }
  12459. EXPECT_EQ("Hello World!", received);
  12460. #else
  12461. EXPECT_FALSE(handle.is_valid());
  12462. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12463. #endif
  12464. }
  12465. {
  12466. // A differently-cased coding must not be mistaken for an unknown one, or
  12467. // the body would be handed back still compressed.
  12468. auto res = cli.Get("/gzipped-uppercase");
  12469. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ("Hello World!", res->body);
  12472. #else
  12473. ASSERT_FALSE(res);
  12474. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12475. #endif
  12476. }
  12477. }
  12478. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12479. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12480. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12481. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12482. // body a second time and appending a second Content-Encoding field line, so
  12483. // clients that decode one coding per listed value handed back raw gzip bytes.
  12484. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12485. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12486. Server svr;
  12487. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12488. // keeps the server from applying a coding of its own.
  12489. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content(gzipped, "text/plain");
  12491. res.set_header("Content-Encoding", "gzip");
  12492. });
  12493. auto port = svr.bind_to_any_port(HOST);
  12494. thread t = thread([&]() { svr.listen_after_bind(); });
  12495. auto se = detail::scope_exit([&] {
  12496. svr.stop();
  12497. t.join();
  12498. ASSERT_FALSE(svr.is_running());
  12499. });
  12500. svr.wait_until_ready();
  12501. Client cli(HOST, port);
  12502. Headers headers = {{"Accept-Encoding", "gzip"}};
  12503. auto res = cli.Get("/pre-gzipped", headers);
  12504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12505. EXPECT_EQ(StatusCode::OK_200, res->status);
  12506. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12507. EXPECT_EQ("Hello World!", res->body);
  12508. }
  12509. // set_compress(false) sends every handler response as it is, buffered or
  12510. // streamed
  12511. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12512. const std::string text(1000, 'a');
  12513. Server svr;
  12514. svr.set_compress(false);
  12515. svr.Get("/buffered", [&](const Request &, Response &res) {
  12516. res.set_content(text, "text/plain");
  12517. });
  12518. svr.Get("/streamed", [&](const Request &, Response &res) {
  12519. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12520. sink.write(text.data(), text.size());
  12521. sink.done();
  12522. return true;
  12523. });
  12524. });
  12525. auto port = svr.bind_to_any_port(HOST);
  12526. ASSERT_LT(0, port);
  12527. thread t = thread([&] { svr.listen_after_bind(); });
  12528. auto se = detail::scope_exit([&] {
  12529. svr.stop();
  12530. t.join();
  12531. ASSERT_FALSE(svr.is_running());
  12532. });
  12533. svr.wait_until_ready();
  12534. Client cli(HOST, port);
  12535. cli.set_decompress(false);
  12536. for (auto path : {"/buffered", "/streamed"}) {
  12537. SCOPED_TRACE(path);
  12538. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12540. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12541. EXPECT_EQ(text, res->body);
  12542. }
  12543. }
  12544. // A chunked provider settles its coding where the headers are written and
  12545. // reuses it at write time. Both ends of that have to hold: a handler's own
  12546. // Content-Encoding suppresses the coding, and a response without one is still
  12547. // compressed as it always was.
  12548. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12549. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12550. const std::string plain = "Hello World! Hello World! Hello World!";
  12551. Server svr;
  12552. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12553. res.set_header("Content-Encoding", "gzip");
  12554. res.set_chunked_content_provider(
  12555. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12556. sink.write(gzipped.data(), gzipped.size());
  12557. sink.done();
  12558. return true;
  12559. });
  12560. });
  12561. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12562. res.set_chunked_content_provider(
  12563. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12564. sink.write(plain.data(), plain.size());
  12565. sink.done();
  12566. return true;
  12567. });
  12568. });
  12569. auto port = svr.bind_to_any_port(HOST);
  12570. thread t = thread([&]() { svr.listen_after_bind(); });
  12571. auto se = detail::scope_exit([&] {
  12572. svr.stop();
  12573. t.join();
  12574. ASSERT_FALSE(svr.is_running());
  12575. });
  12576. svr.wait_until_ready();
  12577. Client cli(HOST, port);
  12578. Headers headers = {{"Accept-Encoding", "gzip"}};
  12579. {
  12580. auto res = cli.Get("/pre-gzipped", headers);
  12581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12582. EXPECT_EQ(StatusCode::OK_200, res->status);
  12583. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12584. EXPECT_EQ("Hello World!", res->body);
  12585. }
  12586. {
  12587. auto res = cli.Get("/negotiated", headers);
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. EXPECT_EQ(StatusCode::OK_200, res->status);
  12590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12591. EXPECT_EQ(plain, res->body);
  12592. }
  12593. }
  12594. #endif
  12595. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12596. // the same message as the comma-joined one, so both have to be read the same
  12597. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12598. // single gzip coding, and a body the sender says was encoded twice was handed
  12599. // back after one pass, still compressed but presented as decoded.
  12600. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12601. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12602. Server svr;
  12603. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12604. res.set_content(body, "image/jpeg");
  12605. res.headers.emplace("Content-Encoding", "gzip");
  12606. res.headers.emplace("Content-Encoding", "gzip");
  12607. });
  12608. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12609. res.set_content(body, "image/jpeg");
  12610. res.set_header("Content-Encoding", "gzip, gzip");
  12611. });
  12612. auto port = svr.bind_to_any_port(HOST);
  12613. thread t = thread([&]() { svr.listen_after_bind(); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. t.join();
  12617. ASSERT_FALSE(svr.is_running());
  12618. });
  12619. svr.wait_until_ready();
  12620. Client cli(HOST, port);
  12621. // Two codings is not something cpp-httplib decodes, so both representations
  12622. // take the pass-through path rather than one of them being gunzipped once.
  12623. for (const char *path : {"/split", "/joined"}) {
  12624. auto res = cli.Get(path);
  12625. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12626. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12627. EXPECT_EQ(body, res->body) << path;
  12628. }
  12629. }
  12630. // Regression test for DoS vulnerability: a malicious server sending a response
  12631. // without Content-Length header must not cause unbounded memory consumption on
  12632. // the client side. The client should stop reading after a reasonable limit,
  12633. // similar to the server-side set_payload_max_length protection.
  12634. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12635. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12636. #ifndef _WIN32
  12637. signal(SIGPIPE, SIG_IGN);
  12638. #endif
  12639. auto server_thread = std::thread([] {
  12640. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12642. default_socket_options(srv);
  12643. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12645. sockaddr_in addr{};
  12646. addr.sin_family = AF_INET;
  12647. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12648. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12649. int opt = 1;
  12650. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12651. #ifdef _WIN32
  12652. reinterpret_cast<const char *>(&opt),
  12653. #else
  12654. &opt,
  12655. #endif
  12656. sizeof(opt));
  12657. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12658. ::listen(srv, 1);
  12659. sockaddr_in cli_addr{};
  12660. socklen_t cli_len = sizeof(cli_addr);
  12661. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12662. if (cli != INVALID_SOCKET) {
  12663. char buf[4096];
  12664. ::recv(cli, buf, sizeof(buf), 0);
  12665. // Malicious response: no Content-Length, no chunked encoding
  12666. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12667. "Connection: close\r\n"
  12668. "\r\n";
  12669. ::send(cli,
  12670. #ifdef _WIN32
  12671. static_cast<const char *>(response_header.c_str()),
  12672. static_cast<int>(response_header.size()),
  12673. #else
  12674. response_header.c_str(), response_header.size(),
  12675. #endif
  12676. 0);
  12677. // Send 10MB of data
  12678. std::string chunk(64 * 1024, 'A');
  12679. size_t total_sent = 0;
  12680. while (total_sent < MALICIOUS_DATA_SIZE) {
  12681. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12682. auto sent = ::send(cli,
  12683. #ifdef _WIN32
  12684. static_cast<const char *>(chunk.c_str()),
  12685. static_cast<int>(to_send),
  12686. #else
  12687. chunk.c_str(), to_send,
  12688. #endif
  12689. 0);
  12690. if (sent <= 0) break;
  12691. total_sent += static_cast<size_t>(sent);
  12692. }
  12693. detail::close_socket(cli);
  12694. }
  12695. detail::close_socket(srv);
  12696. });
  12697. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12698. size_t total_read = 0;
  12699. {
  12700. Client cli("127.0.0.1", PORT + 2);
  12701. cli.set_read_timeout(5, 0);
  12702. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12703. auto stream = cli.open_stream("GET", "/malicious");
  12704. ASSERT_TRUE(stream.is_valid());
  12705. char buffer[64 * 1024];
  12706. ssize_t n;
  12707. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12708. total_read += static_cast<size_t>(n);
  12709. }
  12710. } // StreamHandle and Client destroyed here, closing the socket
  12711. server_thread.join();
  12712. // With set_payload_max_length, the client must stop reading before consuming
  12713. // all 10MB. The read loop should be cut off at or near the configured limit.
  12714. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12715. << "Client read " << total_read << " bytes, exceeding the configured "
  12716. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12717. }
  12718. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12719. // the entire response body without truncation.
  12720. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12721. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12722. #ifndef _WIN32
  12723. signal(SIGPIPE, SIG_IGN);
  12724. #endif
  12725. auto server_thread = std::thread([] {
  12726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12727. default_socket_options(srv);
  12728. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12730. sockaddr_in addr{};
  12731. addr.sin_family = AF_INET;
  12732. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12734. int opt = 1;
  12735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12736. #ifdef _WIN32
  12737. reinterpret_cast<const char *>(&opt),
  12738. #else
  12739. &opt,
  12740. #endif
  12741. sizeof(opt));
  12742. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12743. ::listen(srv, 1);
  12744. sockaddr_in cli_addr{};
  12745. socklen_t cli_len = sizeof(cli_addr);
  12746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12747. if (cli != INVALID_SOCKET) {
  12748. char buf[4096];
  12749. ::recv(cli, buf, sizeof(buf), 0);
  12750. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12751. "Connection: close\r\n"
  12752. "\r\n";
  12753. ::send(cli,
  12754. #ifdef _WIN32
  12755. static_cast<const char *>(response_header.c_str()),
  12756. static_cast<int>(response_header.size()),
  12757. #else
  12758. response_header.c_str(), response_header.size(),
  12759. #endif
  12760. 0);
  12761. std::string chunk(64 * 1024, 'A');
  12762. size_t total_sent = 0;
  12763. while (total_sent < DATA_SIZE) {
  12764. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12765. auto sent = ::send(cli,
  12766. #ifdef _WIN32
  12767. static_cast<const char *>(chunk.c_str()),
  12768. static_cast<int>(to_send),
  12769. #else
  12770. chunk.c_str(), to_send,
  12771. #endif
  12772. 0);
  12773. if (sent <= 0) break;
  12774. total_sent += static_cast<size_t>(sent);
  12775. }
  12776. #ifdef _WIN32
  12777. ::shutdown(cli, SD_SEND);
  12778. #else
  12779. ::shutdown(cli, SHUT_WR);
  12780. #endif
  12781. // Drain until the client closes its end, ensuring all data is delivered
  12782. char drain[1024];
  12783. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12784. detail::close_socket(cli);
  12785. }
  12786. detail::close_socket(srv);
  12787. });
  12788. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12789. size_t total_read = 0;
  12790. {
  12791. Client cli("127.0.0.1", PORT + 2);
  12792. cli.set_read_timeout(5, 0);
  12793. cli.set_payload_max_length(0); // 0 means no limit
  12794. auto stream = cli.open_stream("GET", "/data");
  12795. ASSERT_TRUE(stream.is_valid());
  12796. char buffer[64 * 1024];
  12797. ssize_t n;
  12798. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12799. total_read += static_cast<size_t>(n);
  12800. }
  12801. }
  12802. server_thread.join();
  12803. EXPECT_EQ(total_read, DATA_SIZE)
  12804. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12805. << " bytes without truncation, but only read " << total_read << " bytes.";
  12806. }
  12807. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12808. // enormous Content-Length must not cause the client to pre-allocate a huge
  12809. // response body buffer. The reservation is capped at payload_max_length_, and
  12810. // the read itself fails when the body exceeds the limit.
  12811. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12812. #ifndef _WIN32
  12813. signal(SIGPIPE, SIG_IGN);
  12814. #endif
  12815. auto server_thread = std::thread([] {
  12816. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12817. default_socket_options(srv);
  12818. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12819. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12820. sockaddr_in addr{};
  12821. addr.sin_family = AF_INET;
  12822. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12823. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12824. int opt = 1;
  12825. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12826. #ifdef _WIN32
  12827. reinterpret_cast<const char *>(&opt),
  12828. #else
  12829. &opt,
  12830. #endif
  12831. sizeof(opt));
  12832. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12833. ::listen(srv, 1);
  12834. sockaddr_in cli_addr{};
  12835. socklen_t cli_len = sizeof(cli_addr);
  12836. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12837. if (cli != INVALID_SOCKET) {
  12838. char buf[4096];
  12839. ::recv(cli, buf, sizeof(buf), 0);
  12840. // Malicious response: claim a 20GB body but send only a tiny payload.
  12841. std::string response = "HTTP/1.1 200 OK\r\n"
  12842. "Content-Length: 20000000000\r\n"
  12843. "\r\n"
  12844. "abc";
  12845. ::send(cli,
  12846. #ifdef _WIN32
  12847. static_cast<const char *>(response.c_str()),
  12848. static_cast<int>(response.size()),
  12849. #else
  12850. response.c_str(), response.size(),
  12851. #endif
  12852. 0);
  12853. detail::close_socket(cli);
  12854. }
  12855. detail::close_socket(srv);
  12856. });
  12857. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12858. {
  12859. Client cli("127.0.0.1", PORT + 2);
  12860. cli.set_read_timeout(5, 0);
  12861. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12862. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12863. // (server claims more bytes than payload_max_length permits), but it must
  12864. // not exhaust memory before getting there.
  12865. auto res = cli.Get("/malicious");
  12866. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12867. }
  12868. server_thread.join();
  12869. }
  12870. // Verify that content_receiver bypasses the default payload_max_length,
  12871. // allowing streaming downloads larger than 100MB without requiring an explicit
  12872. // set_payload_max_length call.
  12873. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12874. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12875. #ifndef _WIN32
  12876. signal(SIGPIPE, SIG_IGN);
  12877. #endif
  12878. auto server_thread = std::thread([] {
  12879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12880. default_socket_options(srv);
  12881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12883. sockaddr_in addr{};
  12884. addr.sin_family = AF_INET;
  12885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12887. int opt = 1;
  12888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12889. #ifdef _WIN32
  12890. reinterpret_cast<const char *>(&opt),
  12891. #else
  12892. &opt,
  12893. #endif
  12894. sizeof(opt));
  12895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12896. ::listen(srv, 1);
  12897. sockaddr_in cli_addr{};
  12898. socklen_t cli_len = sizeof(cli_addr);
  12899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12900. if (cli != INVALID_SOCKET) {
  12901. char buf[4096];
  12902. ::recv(cli, buf, sizeof(buf), 0);
  12903. // Response with Content-Length larger than default 100MB limit
  12904. auto content_length = std::to_string(DATA_SIZE);
  12905. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12906. "Content-Length: " +
  12907. content_length +
  12908. "\r\n"
  12909. "Connection: close\r\n"
  12910. "\r\n";
  12911. ::send(cli,
  12912. #ifdef _WIN32
  12913. static_cast<const char *>(response_header.c_str()),
  12914. static_cast<int>(response_header.size()),
  12915. #else
  12916. response_header.c_str(), response_header.size(),
  12917. #endif
  12918. 0);
  12919. std::string chunk(64 * 1024, 'A');
  12920. size_t total_sent = 0;
  12921. while (total_sent < DATA_SIZE) {
  12922. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12923. auto sent = ::send(cli,
  12924. #ifdef _WIN32
  12925. static_cast<const char *>(chunk.c_str()),
  12926. static_cast<int>(to_send),
  12927. #else
  12928. chunk.c_str(), to_send,
  12929. #endif
  12930. 0);
  12931. if (sent <= 0) break;
  12932. total_sent += static_cast<size_t>(sent);
  12933. }
  12934. detail::close_socket(cli);
  12935. }
  12936. detail::close_socket(srv);
  12937. });
  12938. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12939. size_t total_received = 0;
  12940. {
  12941. Client cli("127.0.0.1", PORT + 2);
  12942. cli.set_read_timeout(10, 0);
  12943. // Do NOT call set_payload_max_length — use the default 100MB limit
  12944. auto res =
  12945. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12946. total_received += data_length;
  12947. return true;
  12948. });
  12949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12950. EXPECT_EQ(StatusCode::OK_200, res->status);
  12951. }
  12952. server_thread.join();
  12953. EXPECT_EQ(total_received, DATA_SIZE)
  12954. << "With content_receiver, the client should read all " << DATA_SIZE
  12955. << " bytes despite the default 100MB payload_max_length, but only read "
  12956. << total_received << " bytes.";
  12957. }
  12958. // Verify that an explicit set_payload_max_length smaller than the response is
  12959. // enforced even when a content_receiver is used.
  12960. TEST(ClientVulnerabilityTest,
  12961. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12962. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12963. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12964. #ifndef _WIN32
  12965. signal(SIGPIPE, SIG_IGN);
  12966. #endif
  12967. auto server_thread = std::thread([] {
  12968. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12969. default_socket_options(srv);
  12970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12971. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12972. sockaddr_in addr{};
  12973. addr.sin_family = AF_INET;
  12974. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12975. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12976. int opt = 1;
  12977. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12978. #ifdef _WIN32
  12979. reinterpret_cast<const char *>(&opt),
  12980. #else
  12981. &opt,
  12982. #endif
  12983. sizeof(opt));
  12984. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12985. ::listen(srv, 1);
  12986. sockaddr_in cli_addr{};
  12987. socklen_t cli_len = sizeof(cli_addr);
  12988. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12989. if (cli != INVALID_SOCKET) {
  12990. char buf[4096];
  12991. ::recv(cli, buf, sizeof(buf), 0);
  12992. auto content_length = std::to_string(DATA_SIZE);
  12993. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12994. "Content-Length: " +
  12995. content_length +
  12996. "\r\n"
  12997. "Connection: close\r\n"
  12998. "\r\n";
  12999. ::send(cli,
  13000. #ifdef _WIN32
  13001. static_cast<const char *>(response_header.c_str()),
  13002. static_cast<int>(response_header.size()),
  13003. #else
  13004. response_header.c_str(), response_header.size(),
  13005. #endif
  13006. 0);
  13007. std::string chunk(64 * 1024, 'A');
  13008. size_t total_sent = 0;
  13009. while (total_sent < DATA_SIZE) {
  13010. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13011. auto sent = ::send(cli,
  13012. #ifdef _WIN32
  13013. static_cast<const char *>(chunk.c_str()),
  13014. static_cast<int>(to_send),
  13015. #else
  13016. chunk.c_str(), to_send,
  13017. #endif
  13018. 0);
  13019. if (sent <= 0) break;
  13020. total_sent += static_cast<size_t>(sent);
  13021. }
  13022. detail::close_socket(cli);
  13023. }
  13024. detail::close_socket(srv);
  13025. });
  13026. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13027. size_t total_received = 0;
  13028. {
  13029. Client cli("127.0.0.1", PORT + 2);
  13030. cli.set_read_timeout(10, 0);
  13031. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13032. auto res =
  13033. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13034. total_received += data_length;
  13035. return true;
  13036. });
  13037. // Should fail because 200MB exceeds the explicit 150MB limit
  13038. EXPECT_FALSE(res);
  13039. }
  13040. server_thread.join();
  13041. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13042. << "Client with content_receiver should respect the explicit "
  13043. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13044. << total_received << " bytes.";
  13045. }
  13046. // Verify that an explicit set_payload_max_length larger than the response
  13047. // allows the content_receiver to read all data successfully.
  13048. TEST(ClientVulnerabilityTest,
  13049. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13050. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13051. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13052. #ifndef _WIN32
  13053. signal(SIGPIPE, SIG_IGN);
  13054. #endif
  13055. auto server_thread = std::thread([] {
  13056. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13057. default_socket_options(srv);
  13058. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13059. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13060. sockaddr_in addr{};
  13061. addr.sin_family = AF_INET;
  13062. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13063. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13064. int opt = 1;
  13065. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13066. #ifdef _WIN32
  13067. reinterpret_cast<const char *>(&opt),
  13068. #else
  13069. &opt,
  13070. #endif
  13071. sizeof(opt));
  13072. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13073. ::listen(srv, 1);
  13074. sockaddr_in cli_addr{};
  13075. socklen_t cli_len = sizeof(cli_addr);
  13076. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13077. if (cli != INVALID_SOCKET) {
  13078. char buf[4096];
  13079. ::recv(cli, buf, sizeof(buf), 0);
  13080. auto content_length = std::to_string(DATA_SIZE);
  13081. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13082. "Content-Length: " +
  13083. content_length +
  13084. "\r\n"
  13085. "Connection: close\r\n"
  13086. "\r\n";
  13087. ::send(cli,
  13088. #ifdef _WIN32
  13089. static_cast<const char *>(response_header.c_str()),
  13090. static_cast<int>(response_header.size()),
  13091. #else
  13092. response_header.c_str(), response_header.size(),
  13093. #endif
  13094. 0);
  13095. std::string chunk(64 * 1024, 'A');
  13096. size_t total_sent = 0;
  13097. while (total_sent < DATA_SIZE) {
  13098. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13099. auto sent = ::send(cli,
  13100. #ifdef _WIN32
  13101. static_cast<const char *>(chunk.c_str()),
  13102. static_cast<int>(to_send),
  13103. #else
  13104. chunk.c_str(), to_send,
  13105. #endif
  13106. 0);
  13107. if (sent <= 0) break;
  13108. total_sent += static_cast<size_t>(sent);
  13109. }
  13110. #ifdef _WIN32
  13111. ::shutdown(cli, SD_SEND);
  13112. #else
  13113. ::shutdown(cli, SHUT_WR);
  13114. #endif
  13115. char drain[1024];
  13116. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13117. detail::close_socket(cli);
  13118. }
  13119. detail::close_socket(srv);
  13120. });
  13121. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13122. size_t total_received = 0;
  13123. {
  13124. Client cli("127.0.0.1", PORT + 2);
  13125. cli.set_read_timeout(10, 0);
  13126. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13127. auto res =
  13128. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13129. total_received += data_length;
  13130. return true;
  13131. });
  13132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13133. EXPECT_EQ(StatusCode::OK_200, res->status);
  13134. }
  13135. server_thread.join();
  13136. EXPECT_EQ(total_received, DATA_SIZE)
  13137. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13138. << " bytes (larger than " << DATA_SIZE
  13139. << " bytes response), content_receiver should read all data, but only "
  13140. "read "
  13141. << total_received << " bytes.";
  13142. }
  13143. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13144. // Regression test for "zip bomb" attack on the client side: a malicious server
  13145. // sends a small gzip-compressed response that decompresses to a huge payload.
  13146. // The client must enforce payload_max_length on the decompressed size.
  13147. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13148. constexpr size_t DECOMPRESSED_SIZE =
  13149. 10 * 1024 * 1024; // 10MB after decompression
  13150. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13151. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13152. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13153. std::string compressed;
  13154. {
  13155. httplib::detail::gzip_compressor compressor;
  13156. bool ok =
  13157. compressor.compress(uncompressed.data(), uncompressed.size(),
  13158. /*last=*/true, [&](const char *buf, size_t len) {
  13159. compressed.append(buf, len);
  13160. return true;
  13161. });
  13162. ASSERT_TRUE(ok);
  13163. }
  13164. // Sanity: compressed data should be much smaller than the decompressed size
  13165. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13166. #ifndef _WIN32
  13167. signal(SIGPIPE, SIG_IGN);
  13168. #endif
  13169. // Set up the listening socket in the main thread so the server is guaranteed
  13170. // to be ready before the client connects (eliminates race condition).
  13171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13172. default_socket_options(srv);
  13173. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13175. sockaddr_in addr{};
  13176. addr.sin_family = AF_INET;
  13177. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13178. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13179. int opt = 1;
  13180. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13181. #ifdef _WIN32
  13182. reinterpret_cast<const char *>(&opt),
  13183. #else
  13184. &opt,
  13185. #endif
  13186. sizeof(opt));
  13187. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13188. ASSERT_EQ(0, ::listen(srv, 1));
  13189. auto server_thread = std::thread([&compressed, srv] {
  13190. sockaddr_in cli_addr{};
  13191. socklen_t cli_len = sizeof(cli_addr);
  13192. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13193. if (cli != INVALID_SOCKET) {
  13194. // Read the full HTTP request (until \r\n\r\n)
  13195. char buf[4096];
  13196. size_t total = 0;
  13197. while (total < sizeof(buf)) {
  13198. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13199. if (n <= 0) break;
  13200. total += static_cast<size_t>(n);
  13201. // Check for end of headers
  13202. if (total >= 4) {
  13203. std::string req(buf, total);
  13204. if (req.find("\r\n\r\n") != std::string::npos) break;
  13205. }
  13206. }
  13207. // Malicious response: gzip-compressed body, no Content-Length
  13208. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13209. "Content-Encoding: gzip\r\n"
  13210. "Connection: close\r\n"
  13211. "\r\n";
  13212. ::send(cli,
  13213. #ifdef _WIN32
  13214. static_cast<const char *>(response_header.c_str()),
  13215. static_cast<int>(response_header.size()),
  13216. #else
  13217. response_header.c_str(), response_header.size(),
  13218. #endif
  13219. 0);
  13220. // Send the compressed payload (small on the wire, huge when decompressed)
  13221. size_t total_sent = 0;
  13222. while (total_sent < compressed.size()) {
  13223. auto to_send = std::min(compressed.size() - total_sent,
  13224. static_cast<size_t>(64 * 1024));
  13225. auto sent =
  13226. ::send(cli,
  13227. #ifdef _WIN32
  13228. static_cast<const char *>(compressed.c_str() + total_sent),
  13229. static_cast<int>(to_send),
  13230. #else
  13231. compressed.c_str() + total_sent, to_send,
  13232. #endif
  13233. 0);
  13234. if (sent <= 0) break;
  13235. total_sent += static_cast<size_t>(sent);
  13236. }
  13237. detail::close_socket(cli);
  13238. }
  13239. });
  13240. auto se = detail::scope_exit([&] {
  13241. detail::close_socket(srv);
  13242. server_thread.join();
  13243. });
  13244. size_t total_decompressed = 0;
  13245. {
  13246. Client cli("127.0.0.1", PORT + 3);
  13247. cli.set_read_timeout(5, 0);
  13248. cli.set_decompress(true);
  13249. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13250. auto stream = cli.open_stream("GET", "/zipbomb");
  13251. ASSERT_TRUE(stream.is_valid());
  13252. char buffer[64 * 1024];
  13253. ssize_t n;
  13254. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13255. total_decompressed += static_cast<size_t>(n);
  13256. }
  13257. }
  13258. // The decompressed size must be capped by payload_max_length. Without
  13259. // protection, the client would decompress the full 10MB from a tiny
  13260. // compressed payload, enabling a zip bomb DoS attack.
  13261. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13262. << "Client decompressed " << total_decompressed
  13263. << " bytes from a gzip response. The decompressed size should be "
  13264. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13265. }
  13266. #endif
  13267. TEST(HostAndPortPropertiesTest, NoSSL) {
  13268. httplib::Client cli("www.google.com", 1234);
  13269. ASSERT_EQ("www.google.com", cli.host());
  13270. ASSERT_EQ(1234, cli.port());
  13271. }
  13272. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13273. httplib::Client cli("www.google.com:1234");
  13274. ASSERT_EQ("www.google.com", cli.host());
  13275. ASSERT_EQ(1234, cli.port());
  13276. }
  13277. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13278. // Port number that overflows int — should not crash, client becomes invalid
  13279. httplib::Client cli("http://www.google.com:99999999999999999999");
  13280. ASSERT_FALSE(cli.is_valid());
  13281. }
  13282. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13283. // Port 99999 exceeds valid range (1-65535) — should not crash
  13284. httplib::Client cli("http://www.google.com:99999");
  13285. ASSERT_FALSE(cli.is_valid());
  13286. auto res = cli.Get("/");
  13287. EXPECT_FALSE(res);
  13288. EXPECT_EQ(Error::Connection, res.error());
  13289. }
  13290. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13291. httplib::Client cli("http://user:pass@localhost:1234");
  13292. ASSERT_FALSE(cli.is_valid());
  13293. EXPECT_FALSE(cli.Get("/"));
  13294. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13295. }
  13296. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13297. httplib::Client cli("http://www.google.com:80abc");
  13298. ASSERT_FALSE(cli.is_valid());
  13299. }
  13300. #ifdef CPPHTTPLIB_SSL_ENABLED
  13301. TEST(HostAndPortPropertiesTest, SSL) {
  13302. httplib::SSLClient cli("www.google.com");
  13303. ASSERT_EQ("www.google.com", cli.host());
  13304. ASSERT_EQ(443, cli.port());
  13305. }
  13306. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13307. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13308. std::string cert;
  13309. read_file(CA_CERT_FILE, cert);
  13310. httplib::SSLClient httplib_client("www.google.com");
  13311. // Load CA store first time
  13312. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13313. // Load CA store second time (update)
  13314. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13315. // Verify client is still valid and can make connections
  13316. httplib_client.enable_server_certificate_verification(true);
  13317. auto res = httplib_client.Get("/");
  13318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13319. // Google may return 200 or 301 depending on various factors
  13320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13321. res->status == StatusCode::MovedPermanently_301);
  13322. }
  13323. TEST(SSLClientTest, ServerNameIndication_Online) {
  13324. auto host = "httpbingo.org";
  13325. auto path = std::string{"/get"};
  13326. SSLClient cli(host, 443);
  13327. auto res = cli.Get(path);
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. ASSERT_EQ(StatusCode::OK_200, res->status);
  13330. }
  13331. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13332. // Use a site that will cause SSL verification failure due to self-signed cert
  13333. SSLClient cli("self-signed.badssl.com", 443);
  13334. cli.enable_server_certificate_verification(true);
  13335. auto res = cli.Get("/");
  13336. ASSERT_TRUE(!res);
  13337. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13338. // Verify backend error is captured for SSLServerVerification
  13339. // This occurs when certificate verification fails
  13340. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13341. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13342. EXPECT_NE(0UL, res.ssl_backend_error());
  13343. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13344. res.ssl_error());
  13345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13346. #if !defined(_WIN32) || \
  13347. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13348. // On non-Windows or when Windows Schannel is disabled, the error comes
  13349. // from OpenSSL's verification
  13350. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13351. res.ssl_backend_error());
  13352. #endif
  13353. #endif
  13354. }
  13355. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13356. // Use a site where hostname doesn't match the certificate
  13357. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13358. SSLClient cli("wrong.host.badssl.com", 443);
  13359. cli.enable_server_certificate_verification(true);
  13360. cli.enable_server_hostname_verification(true);
  13361. auto res = cli.Get("/");
  13362. ASSERT_TRUE(!res);
  13363. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13364. // Verify backend error is captured for hostname verification failure
  13365. EXPECT_NE(0UL, res.ssl_backend_error());
  13366. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13367. res.ssl_error());
  13368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13369. #if !defined(_WIN32) || \
  13370. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13371. // On non-Windows or when Windows Schannel is disabled, the error comes
  13372. // from OpenSSL's hostname verification
  13373. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13374. res.ssl_backend_error());
  13375. #endif
  13376. #endif
  13377. }
  13378. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13379. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13380. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13381. SSLClient cli("www.google.com", 443);
  13382. cli.enable_server_certificate_verification(true);
  13383. auto res = cli.Get("/");
  13384. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13385. }
  13386. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13387. SSLClient cli("www.google.com", 443);
  13388. cli.enable_server_certificate_verification(true);
  13389. cli.enable_windows_certificate_verification(false);
  13390. auto res = cli.Get("/");
  13391. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13392. }
  13393. // The server sends an intermediate cross-signed by a root Windows trusts,
  13394. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13395. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13396. SSLClient cli("accounts.spotify.com", 443);
  13397. auto res = cli.Get("/");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13399. << " ssl_backend_error=" << res.ssl_backend_error();
  13400. }
  13401. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13402. // policy status, which no backend reports for a self-signed certificate.
  13403. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13404. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13405. ASSERT_TRUE(svr.is_valid());
  13406. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13407. auto se = detail::scope_exit([&] {
  13408. svr.stop();
  13409. t.join();
  13410. ASSERT_FALSE(svr.is_running());
  13411. });
  13412. svr.wait_until_ready();
  13413. SSLClient cli("127.0.0.1", PORT);
  13414. cli.set_connection_timeout(30);
  13415. auto res = cli.Get("/");
  13416. ASSERT_FALSE(res);
  13417. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13418. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13419. }
  13420. #endif
  13421. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13422. Client cli("https://google.com");
  13423. auto res = cli.Get("/");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13426. }
  13427. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13428. SSLClient cli("google.com");
  13429. cli.set_ca_cert_path(CA_CERT_FILE);
  13430. auto res = cli.Get("/");
  13431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13432. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13433. }
  13434. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13435. SSLClient cli("google.com");
  13436. cli.enable_server_certificate_verification(true);
  13437. cli.set_ca_cert_path("hello");
  13438. auto res = cli.Get("/");
  13439. ASSERT_TRUE(!res);
  13440. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13441. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13442. // should be set
  13443. EXPECT_EQ(0, res.ssl_error());
  13444. // Verify backend error is captured for SSLLoadingCerts
  13445. // This error occurs when loading CA certificates fails
  13446. EXPECT_NE(0UL, res.ssl_backend_error());
  13447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13448. // OpenSSL specific error codes:
  13449. // > openssl errstr 0x80000002
  13450. // error:80000002:system library::No such file or directory
  13451. // > openssl errstr 0xA000126
  13452. // error:0A000126:SSL routines::unexpected eof while reading
  13453. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13454. res.ssl_backend_error() == 0xA000126);
  13455. #endif
  13456. }
  13457. TEST(SSLClientTest, ServerCertificateVerification4) {
  13458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. ASSERT_TRUE(svr.is_valid());
  13460. svr.Get("/test", [&](const Request &, Response &res) {
  13461. res.set_content("test", "text/plain");
  13462. svr.stop();
  13463. ASSERT_TRUE(true);
  13464. });
  13465. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13466. auto se = detail::scope_exit([&] {
  13467. t.join();
  13468. ASSERT_FALSE(svr.is_running());
  13469. });
  13470. svr.wait_until_ready();
  13471. SSLClient cli("127.0.0.1", PORT);
  13472. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13473. cli.enable_server_certificate_verification(true);
  13474. cli.set_connection_timeout(30);
  13475. auto res = cli.Get("/test");
  13476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13477. ASSERT_EQ(StatusCode::OK_200, res->status);
  13478. }
  13479. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13480. std::string cert;
  13481. read_file(CA_CERT_FILE, cert);
  13482. SSLClient cli("google.com");
  13483. cli.load_ca_cert_store(cert.data(), cert.size());
  13484. const auto res = cli.Get("/");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13487. }
  13488. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13489. // clang-format off
  13490. static constexpr char cert[] =
  13491. "GlobalSign Root CA\n"
  13492. "==================\n"
  13493. "-----BEGIN CERTIFICATE-----\n"
  13494. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13495. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13496. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13497. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13498. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13499. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13500. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13501. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13502. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13503. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13504. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13505. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13506. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13507. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13508. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13509. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13510. "-----END CERTIFICATE-----\n";
  13511. // clang-format on
  13512. SSLClient cli("google.com");
  13513. cli.load_ca_cert_store(cert, sizeof(cert));
  13514. const auto res = cli.Get("/");
  13515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13516. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13517. }
  13518. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13519. SSLClient cli("www.youtube.com");
  13520. cli.set_ca_cert_path(CA_CERT_FILE);
  13521. cli.enable_server_certificate_verification(true);
  13522. cli.set_follow_location(true);
  13523. auto res = cli.Get("/");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. ASSERT_EQ(StatusCode::OK_200, res->status);
  13526. }
  13527. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13528. SSLClient cli("wWw.YouTube.Com");
  13529. cli.set_ca_cert_path(CA_CERT_FILE);
  13530. cli.enable_server_certificate_verification(true);
  13531. cli.enable_server_hostname_verification(true);
  13532. cli.set_follow_location(true);
  13533. auto res = cli.Get("/");
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. ASSERT_EQ(StatusCode::OK_200, res->status);
  13536. }
  13537. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13538. SSLClient cli("gOoGlE.COm");
  13539. cli.enable_server_certificate_verification(true);
  13540. cli.enable_server_hostname_verification(true);
  13541. cli.set_follow_location(true);
  13542. auto res = cli.Get("/");
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. ASSERT_EQ(StatusCode::OK_200, res->status);
  13545. }
  13546. TEST(SSLClientTest, Issue2004_Online) {
  13547. Client client("https://google.com");
  13548. client.set_follow_location(true);
  13549. auto res = client.Get("/");
  13550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13551. ASSERT_EQ(StatusCode::OK_200, res->status);
  13552. auto body = res->body;
  13553. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13554. }
  13555. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13556. // Create SSLClient with invalid cert/key to make is_valid() return false
  13557. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13558. "nonexistent_key.pem");
  13559. // is_valid() should be false due to cert loading failure
  13560. ASSERT_FALSE(cli.is_valid());
  13561. auto res = cli.Get("/");
  13562. ASSERT_FALSE(res);
  13563. EXPECT_EQ(Error::SSLConnection, res.error());
  13564. }
  13565. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13566. // Test for Issue #2251: SSL error not properly reported when client cert
  13567. // and key paths are swapped or mismatched
  13568. // This simulates the scenario where user accidentally swaps the cert and key
  13569. // files
  13570. // Using client cert file as private key and vice versa (completely wrong)
  13571. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13572. // Should fail validation due to cert/key mismatch
  13573. ASSERT_FALSE(cli.is_valid());
  13574. // Attempt to make a request should fail with proper error
  13575. auto res = cli.Get("/");
  13576. ASSERT_FALSE(res);
  13577. EXPECT_EQ(Error::SSLConnection, res.error());
  13578. // SSL error should be recorded in the Result object (this is the key fix for
  13579. // Issue #2251)
  13580. auto backend_error = res.ssl_backend_error();
  13581. EXPECT_NE(0u, backend_error);
  13582. }
  13583. // Tests cert/key mismatch detection at the TLS context level
  13584. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13585. // Test that using mismatched cert/key causes connection failure.
  13586. // We verify this at the SSLClient level rather than through internal
  13587. // TLS API functions.
  13588. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13589. cli.enable_server_certificate_verification(false);
  13590. cli.set_connection_timeout(2);
  13591. // The mismatch should cause a connection or handshake error
  13592. auto res = cli.Get("/test");
  13593. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13594. // Either way, the request should fail
  13595. EXPECT_FALSE(res);
  13596. }
  13597. #endif
  13598. #if 0
  13599. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13600. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13601. ASSERT_TRUE(cli != nullptr);
  13602. cli->set_address_family(AF_INET6);
  13603. cli->set_interface("en0");
  13604. auto res = cli->Get("/get");
  13605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13606. ASSERT_EQ(StatusCode::OK_200, res->status);
  13607. }
  13608. #endif
  13609. // Client certificate tests - work with all TLS backends
  13610. #ifdef CPPHTTPLIB_SSL_ENABLED
  13611. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13612. void ClientCertPresent(
  13613. const std::string &client_cert_file,
  13614. const std::string &client_private_key_file,
  13615. const std::string &client_encrypted_private_key_pass = std::string(),
  13616. const ClientCertServerSetup &setup = nullptr) {
  13617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13618. ASSERT_TRUE(svr.is_valid());
  13619. if (setup) { setup(svr); }
  13620. svr.Get("/test", [&](const Request &req, Response &res) {
  13621. res.set_content("test", "text/plain");
  13622. auto cert = req.peer_cert();
  13623. ASSERT_TRUE(static_cast<bool>(cert));
  13624. std::string common_name = cert.subject_cn();
  13625. EXPECT_EQ("Common Name", common_name);
  13626. });
  13627. auto port = svr.bind_to_any_port(HOST);
  13628. ASSERT_LT(0, port);
  13629. thread t = thread([&]() { svr.listen_after_bind(); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. t.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13637. client_encrypted_private_key_pass);
  13638. cli.enable_server_certificate_verification(false);
  13639. cli.set_connection_timeout(30);
  13640. auto res = cli.Get("/test");
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. ASSERT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(SSLClientServerTest, ClientCertPresent) {
  13645. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13646. }
  13647. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13648. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13649. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13650. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13651. }
  13652. // Expects svr, which must require client certificates, to reject a client
  13653. // that has none
  13654. void RejectsClientWithoutCert(SSLServer &svr) {
  13655. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13656. auto port = svr.bind_to_any_port(HOST);
  13657. ASSERT_LT(0, port);
  13658. thread t = thread([&]() { svr.listen_after_bind(); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. t.join();
  13662. ASSERT_FALSE(svr.is_running());
  13663. });
  13664. svr.wait_until_ready();
  13665. SSLClient cli(HOST, port);
  13666. cli.set_connection_timeout(30);
  13667. // Skip the server certificate check, so that the request fails because the
  13668. // client certificate is missing rather than because cert.pem is not trusted
  13669. cli.enable_server_certificate_verification(false);
  13670. auto res = cli.Get("/test");
  13671. ASSERT_FALSE(res);
  13672. // The server rejects the client during the handshake, or on TLS 1.3 right
  13673. // after it, which the client notices on its first write or read
  13674. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13675. res.error() == Error::Write || res.error() == Error::Read)
  13676. << to_string(res.error());
  13677. if (res.error() == Error::SSLConnection) {
  13678. EXPECT_NE(0UL, res.ssl_backend_error());
  13679. }
  13680. // A rejection noticed on the write keeps the TLS error the write hit
  13681. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13682. }
  13683. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13685. ASSERT_TRUE(svr.is_valid());
  13686. if (setup) { setup(svr); }
  13687. RejectsClientWithoutCert(svr);
  13688. }
  13689. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13690. // A server that requires client certificates must keep requiring them after
  13691. // setup changes it, and keep accepting a client that has one
  13692. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13693. ClientCertMissing(setup);
  13694. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13695. setup);
  13696. }
  13697. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13698. ClientCertStillRequired([](SSLServer &svr) {
  13699. ASSERT_TRUE(tls::set_verify_callback(
  13700. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13701. });
  13702. }
  13703. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13704. ClientCertStillRequired([](SSLServer &svr) {
  13705. ASSERT_TRUE(tls::set_verify_callback(
  13706. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13707. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13708. });
  13709. }
  13710. // The client verifies the server certificate during the handshake, so a
  13711. // server that fails the check never gets the client certificate, even when a
  13712. // verifier of the client's own accepts it
  13713. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13714. struct Case {
  13715. const char *trusted_ca;
  13716. const char *host;
  13717. Error error;
  13718. };
  13719. // cert2.pem names localhost: the first client does not trust it, and the
  13720. // second trusts it but asks for another name
  13721. for (const auto &c :
  13722. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13723. Case{SERVER_CERT2_FILE, "example.com",
  13724. Error::SSLServerHostnameVerification}}) {
  13725. for (auto with_verifier : {false, true}) {
  13726. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13727. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13728. CLIENT_CA_CERT_FILE);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. std::atomic<bool> got_client_cert{false};
  13731. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13732. [&](const tls::VerifyContext &) {
  13733. got_client_cert = true;
  13734. return true;
  13735. }));
  13736. auto port = svr.bind_to_any_port("127.0.0.1");
  13737. ASSERT_LT(0, port);
  13738. thread t = thread([&] { svr.listen_after_bind(); });
  13739. svr.wait_until_ready();
  13740. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13741. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13742. cli.set_ca_cert_path(c.trusted_ca);
  13743. if (with_verifier) {
  13744. cli.set_server_certificate_verifier(
  13745. [](const tls::VerifyContext &) { return true; });
  13746. }
  13747. auto res = cli.Get("/");
  13748. EXPECT_FALSE(res);
  13749. EXPECT_EQ(c.error, res.error());
  13750. svr.stop();
  13751. t.join();
  13752. EXPECT_FALSE(got_client_cert);
  13753. }
  13754. }
  13755. }
  13756. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13757. std::string cert_pem, key_pem, ca_pem;
  13758. read_file(SERVER_CERT_FILE, cert_pem);
  13759. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13760. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13761. ASSERT_TRUE(
  13762. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13763. }
  13764. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13766. ASSERT_TRUE(svr.is_valid());
  13767. UpdateCertsPemWithClientCA(svr);
  13768. RejectsClientWithoutCert(svr);
  13769. }
  13770. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13771. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13772. }
  13773. // A TLS error from one request must not show up in a later request's Result
  13774. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13776. ASSERT_TRUE(svr.is_valid());
  13777. svr.Get("/test", [](const Request &, Response &res) {
  13778. res.set_content("test", "text/plain");
  13779. });
  13780. auto port = svr.bind_to_any_port(HOST);
  13781. ASSERT_LT(0, port);
  13782. thread t = thread([&]() { svr.listen_after_bind(); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. ASSERT_FALSE(svr.is_running());
  13787. });
  13788. svr.wait_until_ready();
  13789. SSLClient cli(HOST, port);
  13790. cli.set_connection_timeout(30);
  13791. cli.enable_server_hostname_verification(false);
  13792. // cert.pem is not trusted, so the handshake fails
  13793. ASSERT_FALSE(cli.Get("/test"));
  13794. cli.enable_server_certificate_verification(false);
  13795. auto res = cli.Get("/test");
  13796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13797. EXPECT_EQ(0, res.ssl_error());
  13798. EXPECT_EQ(0UL, res.ssl_backend_error());
  13799. }
  13800. // PEM memory-based constructor tests (works with all TLS backends).
  13801. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13802. // terminator after it.
  13803. void PemMemoryClientCertPresent(
  13804. const std::string &client_cert_file,
  13805. const std::string &client_private_key_file,
  13806. const std::string &client_encrypted_private_key_pass = std::string(),
  13807. bool exact_size = false) {
  13808. // Read PEM files into memory
  13809. std::string server_cert_pem, server_key_pem;
  13810. std::string client_ca_pem;
  13811. std::string client_cert_pem, client_key_pem;
  13812. read_file(SERVER_CERT_FILE, server_cert_pem);
  13813. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13814. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13815. read_file(client_cert_file, client_cert_pem);
  13816. read_file(client_private_key_file, client_key_pem);
  13817. std::list<std::vector<char>> exact_copies;
  13818. auto data = [&](const std::string &pem) -> const char * {
  13819. if (!exact_size) { return pem.c_str(); }
  13820. exact_copies.emplace_back(pem.begin(), pem.end());
  13821. return exact_copies.back().data();
  13822. };
  13823. // Create server with PEM memory
  13824. SSLServer::PemMemory server_pem = {
  13825. data(server_cert_pem),
  13826. server_cert_pem.size(),
  13827. data(server_key_pem),
  13828. server_key_pem.size(),
  13829. data(client_ca_pem),
  13830. client_ca_pem.size(),
  13831. nullptr // no password for server key
  13832. };
  13833. SSLServer svr(server_pem);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. svr.Get("/test", [&](const Request &req, Response &res) {
  13836. res.set_content("test", "text/plain");
  13837. auto cert = req.peer_cert();
  13838. ASSERT_TRUE(static_cast<bool>(cert));
  13839. EXPECT_EQ("Common Name", cert.subject_cn());
  13840. });
  13841. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13842. auto se = detail::scope_exit([&] {
  13843. svr.stop();
  13844. t.join();
  13845. ASSERT_FALSE(svr.is_running());
  13846. });
  13847. svr.wait_until_ready();
  13848. // Create client with PEM memory
  13849. const char *password = client_encrypted_private_key_pass.empty()
  13850. ? nullptr
  13851. : client_encrypted_private_key_pass.c_str();
  13852. SSLClient::PemMemory client_pem = {
  13853. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13854. client_key_pem.size(), password};
  13855. SSLClient cli(HOST, PORT, client_pem);
  13856. cli.enable_server_certificate_verification(false);
  13857. cli.set_connection_timeout(30);
  13858. auto res = cli.Get("/test");
  13859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13860. ASSERT_EQ(StatusCode::OK_200, res->status);
  13861. }
  13862. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13863. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13864. }
  13865. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13866. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13867. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13868. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13869. }
  13870. // A server built from PEM memory with a client CA requires client certificates,
  13871. // also when the CA is a NUL-terminated string passed with a length of 0
  13872. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13873. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13874. read_file(SERVER_CERT_FILE, server_cert_pem);
  13875. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13876. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13877. SSLServer::PemMemory server_pem = {
  13878. server_cert_pem.c_str(),
  13879. server_cert_pem.size(),
  13880. server_key_pem.c_str(),
  13881. server_key_pem.size(),
  13882. client_ca_pem.c_str(),
  13883. client_ca_pem.size(),
  13884. nullptr // no password for server key
  13885. };
  13886. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13887. SCOPED_TRACE(client_ca_pem_len);
  13888. server_pem.client_ca_pem_len = client_ca_pem_len;
  13889. SSLServer svr(server_pem);
  13890. ASSERT_TRUE(svr.is_valid());
  13891. RejectsClientWithoutCert(svr);
  13892. }
  13893. // An empty CA fails to load instead of turning the check off
  13894. server_pem.client_ca_pem = "";
  13895. server_pem.client_ca_pem_len = 0;
  13896. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13897. }
  13898. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13899. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13900. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13901. true);
  13902. }
  13903. // A length shorter than the PEM cuts it short, so it no longer loads
  13904. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13905. std::string cert, key;
  13906. read_file(SERVER_CERT_FILE, cert);
  13907. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13908. for (auto cut_cert : {true, false}) {
  13909. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13910. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13911. SSLServer::PemMemory server_pem = {
  13912. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13913. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13914. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13915. key_len, nullptr};
  13916. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13917. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13918. key.c_str(), key_len, nullptr};
  13919. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13920. }
  13921. }
  13922. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13923. class NoListenSSLServer : public SSLServer {
  13924. public:
  13925. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13926. const char *client_ca_cert_file_path,
  13927. const char *client_ca_cert_dir_path = nullptr)
  13928. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13929. client_ca_cert_dir_path),
  13930. stop_(false) {}
  13931. std::atomic_bool stop_;
  13932. private:
  13933. bool process_and_close_socket(socket_t /*sock*/) override {
  13934. // Don't create SSL context
  13935. while (!stop_.load()) {
  13936. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13937. }
  13938. return true;
  13939. }
  13940. };
  13941. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13942. CLIENT_CA_CERT_FILE);
  13943. ASSERT_TRUE(svr.is_valid());
  13944. svr.Get("/test", [&](const Request &, Response &res) {
  13945. res.set_content("test", "text/plain");
  13946. });
  13947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop_ = true;
  13950. svr.stop();
  13951. t.join();
  13952. ASSERT_FALSE(svr.is_running());
  13953. });
  13954. svr.wait_until_ready();
  13955. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13956. cli.enable_server_certificate_verification(false);
  13957. cli.set_connection_timeout(1);
  13958. auto res = cli.Get("/test");
  13959. ASSERT_TRUE(!res);
  13960. EXPECT_EQ(Error::SSLConnection, res.error());
  13961. // Timeout results in WantRead error code (maps to backend-specific value)
  13962. EXPECT_NE(0, res.ssl_error());
  13963. }
  13964. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13965. // Test SSLServer with client certificate verification using the standard
  13966. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13968. CLIENT_CA_CERT_DIR);
  13969. ASSERT_TRUE(svr.is_valid());
  13970. svr.Get("/test", [&](const Request &req, Response &res) {
  13971. res.set_content("test", "text/plain");
  13972. auto cert = req.peer_cert();
  13973. ASSERT_TRUE(static_cast<bool>(cert));
  13974. auto common_name = cert.subject_cn();
  13975. EXPECT_EQ("Common Name", common_name);
  13976. });
  13977. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13978. auto se = detail::scope_exit([&] {
  13979. svr.stop();
  13980. t.join();
  13981. ASSERT_FALSE(svr.is_running());
  13982. });
  13983. svr.wait_until_ready();
  13984. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13985. cli.enable_server_certificate_verification(false);
  13986. cli.set_connection_timeout(30);
  13987. auto res = cli.Get("/test");
  13988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13989. ASSERT_EQ(StatusCode::OK_200, res->status);
  13990. }
  13991. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13992. // Verifies that wildcard matching and exact matching work consistently
  13993. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13994. using namespace httplib::tls;
  13995. // We need a running server to test against
  13996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. svr.Get("/test", [](const Request &, Response &res) {
  13999. res.set_content("ok", "text/plain");
  14000. });
  14001. thread t([&]() { svr.listen(HOST, PORT); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. });
  14006. svr.wait_until_ready();
  14007. bool verify_callback_called = false;
  14008. bool verify_result_wrong = false;
  14009. SSLClient cli(HOST, PORT);
  14010. cli.enable_server_certificate_verification(true);
  14011. cli.set_ca_cert_path(CA_CERT_FILE);
  14012. cli.set_connection_timeout(5);
  14013. // Note: Test certificate has CN="Common Name", not "localhost"
  14014. bool verify_result_cn = false;
  14015. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14016. verify_callback_called = true;
  14017. if (!ctx.cert) return false;
  14018. // Test 1: "Common Name" should match (our test server cert CN)
  14019. verify_result_cn = ctx.check_hostname("Common Name");
  14020. // Test 2: wrong hostname should not match
  14021. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14022. return true; // Accept for the purpose of this test
  14023. });
  14024. auto res = cli.Get("/test");
  14025. // The request may succeed or fail depending on cert configuration
  14026. // but the callback should have been called
  14027. ASSERT_TRUE(verify_callback_called)
  14028. << "Verify callback should have been called";
  14029. // CN="Common Name" should match our test certificate
  14030. //
  14031. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14032. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14033. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14034. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14035. // <openssl/base.h>, which is included transitively when
  14036. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14037. #if defined(OPENSSL_IS_BORINGSSL)
  14038. EXPECT_FALSE(verify_result_cn)
  14039. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14040. #else
  14041. EXPECT_TRUE(verify_result_cn)
  14042. << "verify_hostname should match 'Common Name' (certificate CN)";
  14043. #endif
  14044. // Wrong hostname should not match
  14045. EXPECT_FALSE(verify_result_wrong)
  14046. << "verify_hostname should not match 'wronghost.example.com'";
  14047. }
  14048. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14049. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14050. // X509_check_ip behavior and must hold for every backend.
  14051. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14052. using namespace httplib::tls;
  14053. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14054. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14055. ASSERT_TRUE(svr.is_valid());
  14056. svr.Get("/test", [](const Request &, Response &res) {
  14057. res.set_content("ok", "text/plain");
  14058. });
  14059. thread t([&]() { svr.listen(HOST, PORT); });
  14060. auto se = detail::scope_exit([&] {
  14061. svr.stop();
  14062. t.join();
  14063. });
  14064. svr.wait_until_ready();
  14065. bool verify_callback_called = false;
  14066. bool ip_matched_via_cn = true;
  14067. SSLClient cli(HOST, PORT);
  14068. cli.enable_server_certificate_verification(true);
  14069. cli.set_ca_cert_path(CA_CERT_FILE);
  14070. cli.set_connection_timeout(5);
  14071. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14072. verify_callback_called = true;
  14073. if (!ctx.cert) return false;
  14074. // The IP appears only in the CN, so it must NOT be accepted.
  14075. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14076. return true; // Accept for the purpose of this test
  14077. });
  14078. cli.Get("/test");
  14079. ASSERT_TRUE(verify_callback_called)
  14080. << "Verify callback should have been called";
  14081. EXPECT_FALSE(ip_matched_via_cn)
  14082. << "An IP host must not be authenticated via the certificate CN";
  14083. }
  14084. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14085. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14086. using namespace httplib::tls;
  14087. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14088. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14089. ASSERT_TRUE(svr.is_valid());
  14090. svr.Get("/test", [](const Request &, Response &res) {
  14091. res.set_content("ok", "text/plain");
  14092. });
  14093. thread t([&]() { svr.listen(HOST, PORT); });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. t.join();
  14097. });
  14098. svr.wait_until_ready();
  14099. bool verify_callback_called = false;
  14100. bool san_matched = false;
  14101. bool wrong_ipv6_matched = true;
  14102. bool cn_ipv6_matched = true;
  14103. SSLClient cli(HOST, PORT);
  14104. cli.enable_server_certificate_verification(true);
  14105. cli.set_ca_cert_path(CA_CERT_FILE);
  14106. cli.set_connection_timeout(5);
  14107. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14108. verify_callback_called = true;
  14109. if (!ctx.cert) return false;
  14110. // Matches the IPv6 iPAddress SAN.
  14111. san_matched = ctx.check_hostname("2001:db8::1");
  14112. // A different IPv6 address must not match.
  14113. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14114. // "::1" lives only in the CN, so it must not be accepted.
  14115. cn_ipv6_matched = ctx.check_hostname("::1");
  14116. return true; // Accept for the purpose of this test
  14117. });
  14118. cli.Get("/test");
  14119. ASSERT_TRUE(verify_callback_called)
  14120. << "Verify callback should have been called";
  14121. EXPECT_TRUE(san_matched)
  14122. << "verify_hostname should match an IPv6 iPAddress SAN";
  14123. EXPECT_FALSE(wrong_ipv6_matched)
  14124. << "verify_hostname should not match a non-matching IPv6 address";
  14125. EXPECT_FALSE(cn_ipv6_matched)
  14126. << "An IPv6 host must not be authenticated via the certificate CN";
  14127. }
  14128. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14129. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14130. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14131. using namespace httplib::tls;
  14132. // SANs: DNS:a.zz, IP:42.46.122.122
  14133. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14134. ASSERT_TRUE(svr.is_valid());
  14135. svr.Get("/test", [](const Request &, Response &res) {
  14136. res.set_content("ok", "text/plain");
  14137. });
  14138. auto port = svr.bind_to_any_port(HOST);
  14139. thread t([&]() { svr.listen_after_bind(); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. });
  14144. svr.wait_until_ready();
  14145. bool verify_callback_called = false;
  14146. bool dns_san_matched = false;
  14147. bool ip_san_matched = false;
  14148. bool ip_matched_via_dns_san = true;
  14149. bool dns_matched_via_ip_san = true;
  14150. bool cn_matched_next_to_dns_san = true;
  14151. SSLClient cli(HOST, port);
  14152. cli.enable_server_certificate_verification(true);
  14153. cli.set_ca_cert_path(CA_CERT_FILE);
  14154. cli.set_connection_timeout(5);
  14155. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14156. verify_callback_called = true;
  14157. if (!ctx.cert) return false;
  14158. dns_san_matched = ctx.check_hostname("a.zz");
  14159. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14160. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14161. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14162. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14163. return true; // Accept for the purpose of this test
  14164. });
  14165. cli.Get("/test");
  14166. ASSERT_TRUE(verify_callback_called)
  14167. << "Verify callback should have been called";
  14168. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14169. EXPECT_TRUE(ip_san_matched)
  14170. << "verify_hostname should match an iPAddress SAN";
  14171. EXPECT_FALSE(ip_matched_via_dns_san)
  14172. << "An IP host must not be authenticated via a dNSName SAN";
  14173. EXPECT_FALSE(dns_matched_via_ip_san)
  14174. << "A DNS host must not be authenticated via an iPAddress SAN";
  14175. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14176. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14177. }
  14178. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14179. // "www.*.example.test" names one host and not every host under example.test.
  14180. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14181. using namespace httplib::tls;
  14182. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14183. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14184. ASSERT_TRUE(svr.is_valid());
  14185. svr.Get("/test", [](const Request &, Response &res) {
  14186. res.set_content("ok", "text/plain");
  14187. });
  14188. auto port = svr.bind_to_any_port(HOST);
  14189. thread t([&]() { svr.listen_after_bind(); });
  14190. auto se = detail::scope_exit([&] {
  14191. svr.stop();
  14192. t.join();
  14193. });
  14194. svr.wait_until_ready();
  14195. bool verify_callback_called = false;
  14196. bool leftmost_wildcard_matched = false;
  14197. bool wildcard_spanned_labels = true;
  14198. bool inner_wildcard_matched = true;
  14199. SSLClient cli(HOST, port);
  14200. cli.enable_server_certificate_verification(true);
  14201. cli.set_ca_cert_path(CA_CERT_FILE);
  14202. cli.set_connection_timeout(5);
  14203. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14204. verify_callback_called = true;
  14205. if (!ctx.cert) return false;
  14206. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14207. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14208. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14209. return true; // Accept for the purpose of this test
  14210. });
  14211. cli.Get("/test");
  14212. ASSERT_TRUE(verify_callback_called)
  14213. << "Verify callback should have been called";
  14214. EXPECT_TRUE(leftmost_wildcard_matched)
  14215. << "A leftmost wildcard should match a single label";
  14216. EXPECT_FALSE(wildcard_spanned_labels)
  14217. << "A wildcard label must not match more than one label";
  14218. EXPECT_FALSE(inner_wildcard_matched)
  14219. << "A wildcard outside the leftmost label must not be honoured";
  14220. }
  14221. // sans() must report each SAN entry under its own type.
  14222. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14223. using namespace httplib::tls;
  14224. // SANs: DNS:a.zz, IP:42.46.122.122
  14225. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14226. ASSERT_TRUE(svr.is_valid());
  14227. svr.Get("/test", [](const Request &, Response &res) {
  14228. res.set_content("ok", "text/plain");
  14229. });
  14230. auto port = svr.bind_to_any_port(HOST);
  14231. thread t([&]() { svr.listen_after_bind(); });
  14232. auto se = detail::scope_exit([&] {
  14233. svr.stop();
  14234. t.join();
  14235. });
  14236. svr.wait_until_ready();
  14237. bool verify_callback_called = false;
  14238. std::vector<SanEntry> sans;
  14239. SSLClient cli(HOST, port);
  14240. cli.enable_server_certificate_verification(true);
  14241. cli.set_ca_cert_path(CA_CERT_FILE);
  14242. cli.set_connection_timeout(5);
  14243. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14244. verify_callback_called = true;
  14245. if (!ctx.cert) return false;
  14246. sans = ctx.sans();
  14247. return true; // Accept for the purpose of this test
  14248. });
  14249. cli.Get("/test");
  14250. ASSERT_TRUE(verify_callback_called)
  14251. << "Verify callback should have been called";
  14252. auto has_san = [&](SanType type, const std::string &value) {
  14253. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14254. return san.type == type && san.value == value;
  14255. });
  14256. };
  14257. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14258. << "sans() should report the dNSName SAN";
  14259. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14260. << "sans() should report the iPAddress SAN";
  14261. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14262. << "sans() must not report the dNSName SAN as an address";
  14263. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14264. << "sans() must not report the iPAddress SAN as a DNS name";
  14265. }
  14266. #endif
  14267. // mbedTLS-specific callback constructor test
  14268. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14269. #ifdef CPPHTTPLIB_SSL_ENABLED
  14270. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14272. ASSERT_TRUE(svr.is_valid());
  14273. // Set up a handler to verify client certificate is present
  14274. bool client_cert_verified = false;
  14275. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14276. // Verify that client certificate was provided
  14277. client_cert_verified = true;
  14278. res.set_content("success", "text/plain");
  14279. });
  14280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14281. auto se = detail::scope_exit([&] {
  14282. svr.stop();
  14283. t.join();
  14284. ASSERT_FALSE(svr.is_running());
  14285. });
  14286. svr.wait_until_ready();
  14287. // Client with certificate
  14288. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14289. cli.enable_server_certificate_verification(false);
  14290. cli.set_connection_timeout(30);
  14291. auto res = cli.Get("/test");
  14292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14293. ASSERT_EQ(StatusCode::OK_200, res->status);
  14294. ASSERT_TRUE(client_cert_verified);
  14295. EXPECT_EQ("success", res->body);
  14296. }
  14297. #endif
  14298. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14299. // backends
  14300. #ifdef CPPHTTPLIB_SSL_ENABLED
  14301. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14302. using namespace httplib::tls;
  14303. // Test that when client CA cert file is provided,
  14304. // the server properly requests and validates client certificates
  14305. // Create a server with client authentication
  14306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. bool handler_called = false;
  14309. svr.Get("/test", [&](const Request &req, Response &res) {
  14310. handler_called = true;
  14311. // Verify that a client certificate was provided
  14312. auto cert = req.peer_cert();
  14313. ASSERT_TRUE(static_cast<bool>(cert));
  14314. // Get the issuer name
  14315. std::string issuer_str = cert.issuer_name();
  14316. ASSERT_FALSE(issuer_str.empty());
  14317. // The client certificate should be issued by our test CA
  14318. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14319. res.set_content("authenticated", "text/plain");
  14320. });
  14321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14322. auto se = detail::scope_exit([&] {
  14323. svr.stop();
  14324. t.join();
  14325. ASSERT_FALSE(svr.is_running());
  14326. });
  14327. svr.wait_until_ready();
  14328. // Connect with a client certificate issued by the CA
  14329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14330. cli.enable_server_certificate_verification(false);
  14331. cli.set_connection_timeout(30);
  14332. auto res = cli.Get("/test");
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. ASSERT_EQ(StatusCode::OK_200, res->status);
  14335. ASSERT_TRUE(handler_called);
  14336. EXPECT_EQ("authenticated", res->body);
  14337. }
  14338. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14339. using namespace httplib::tls;
  14340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14341. ASSERT_TRUE(svr.is_valid());
  14342. svr.Get("/test", [](const Request &, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. });
  14350. svr.wait_until_ready();
  14351. SSLClient cli(HOST, PORT);
  14352. cli.enable_server_certificate_verification(false);
  14353. cli.set_connection_timeout(30);
  14354. bool cert_checked = false;
  14355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14356. if (ctx.cert) {
  14357. auto sans = ctx.sans();
  14358. // Test certificate may or may not have SANs - just verify the API
  14359. // works If SANs exist, verify the types are valid
  14360. for (const auto &san : sans) {
  14361. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14362. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14363. san.type == SanType::OTHER);
  14364. EXPECT_FALSE(san.value.empty());
  14365. }
  14366. cert_checked = true;
  14367. }
  14368. return true;
  14369. });
  14370. auto res = cli.Get("/test");
  14371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14372. EXPECT_TRUE(cert_checked);
  14373. }
  14374. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14375. using namespace httplib::tls;
  14376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14377. ASSERT_TRUE(svr.is_valid());
  14378. svr.Get("/test", [](const Request &, Response &res) {
  14379. res.set_content("ok", "text/plain");
  14380. });
  14381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14382. auto se = detail::scope_exit([&] {
  14383. svr.stop();
  14384. t.join();
  14385. });
  14386. svr.wait_until_ready();
  14387. SSLClient cli(HOST, PORT);
  14388. cli.enable_server_certificate_verification(false);
  14389. cli.set_connection_timeout(30);
  14390. bool validity_checked = false;
  14391. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14392. if (ctx.cert) {
  14393. time_t not_before = 0, not_after = 0;
  14394. bool result = ctx.validity(not_before, not_after);
  14395. EXPECT_TRUE(result);
  14396. // Verify that not_before < now < not_after for a valid cert
  14397. time_t now = time(nullptr);
  14398. EXPECT_LT(not_before, now);
  14399. EXPECT_GT(not_after, now);
  14400. validity_checked = true;
  14401. }
  14402. return true;
  14403. });
  14404. auto res = cli.Get("/test");
  14405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14406. EXPECT_TRUE(validity_checked);
  14407. }
  14408. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14409. using namespace httplib::tls;
  14410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14411. ASSERT_TRUE(svr.is_valid());
  14412. svr.Get("/test", [](const Request &, Response &res) {
  14413. res.set_content("ok", "text/plain");
  14414. });
  14415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. });
  14420. svr.wait_until_ready();
  14421. SSLClient cli(HOST, PORT);
  14422. cli.enable_server_certificate_verification(false);
  14423. cli.set_connection_timeout(30);
  14424. bool serial_checked = false;
  14425. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14426. if (ctx.cert) {
  14427. std::string serial = ctx.serial();
  14428. EXPECT_FALSE(serial.empty());
  14429. // Serial should be a hex string
  14430. for (char c : serial) {
  14431. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14432. (c >= 'a' && c <= 'f'));
  14433. }
  14434. serial_checked = true;
  14435. }
  14436. return true;
  14437. });
  14438. auto res = cli.Get("/test");
  14439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14440. EXPECT_TRUE(serial_checked);
  14441. }
  14442. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14443. // Test 1: Valid CA file - no error should be recorded
  14444. {
  14445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14446. CLIENT_CA_CERT_FILE);
  14447. ASSERT_TRUE(svr.is_valid());
  14448. // With valid setup, last_ssl_error should be 0
  14449. EXPECT_EQ(0, svr.ssl_last_error());
  14450. }
  14451. // Test 2: Invalid CA file content
  14452. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14453. {
  14454. // Create a temporary file with completely invalid content
  14455. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14456. {
  14457. std::ofstream ofs(temp_invalid_ca);
  14458. ofs << "This is not a certificate file at all\n";
  14459. ofs << "Just plain text content\n";
  14460. }
  14461. // Create server with invalid CA file
  14462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14463. // Clean up temporary file
  14464. std::remove(temp_invalid_ca);
  14465. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14466. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14467. // Note: SSL_CTX_load_verify_locations typically fails first,
  14468. // but our error handling code path is still exercised
  14469. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14470. }
  14471. }
  14472. TEST(VerifyCallbackTest, VerifyContextFields) {
  14473. using namespace httplib::tls;
  14474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14475. ASSERT_TRUE(svr.is_valid());
  14476. svr.Get("/test", [](const Request &, Response &res) {
  14477. res.set_content("ok", "text/plain");
  14478. });
  14479. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14480. auto se = detail::scope_exit([&] {
  14481. svr.stop();
  14482. t.join();
  14483. });
  14484. svr.wait_until_ready();
  14485. SSLClient cli(HOST, PORT);
  14486. cli.enable_server_certificate_verification(false);
  14487. cli.set_connection_timeout(30);
  14488. int callback_count = 0;
  14489. bool saw_leaf_cert = false;
  14490. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14491. if (ctx.cert) {
  14492. callback_count++;
  14493. // We should see at least one certificate (the leaf)
  14494. std::string cn = ctx.subject_cn();
  14495. if (!cn.empty()) { saw_leaf_cert = true; }
  14496. // Verify context fields are populated
  14497. EXPECT_NE(ctx.session, nullptr);
  14498. EXPECT_GE(ctx.depth, 0);
  14499. }
  14500. return true;
  14501. });
  14502. auto res = cli.Get("/test");
  14503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14504. EXPECT_GT(callback_count, 0);
  14505. EXPECT_TRUE(saw_leaf_cert);
  14506. }
  14507. // A verifier that accepts runs alongside the built-in verification, and is the
  14508. // only check once that is turned off.
  14509. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14510. using namespace httplib::tls;
  14511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14512. ASSERT_TRUE(svr.is_valid());
  14513. svr.Get("/test", [](const Request &, Response &res) {
  14514. res.set_content("ok", "text/plain");
  14515. });
  14516. auto port = svr.bind_to_any_port(HOST);
  14517. thread t([&]() { svr.listen_after_bind(); });
  14518. auto se = detail::scope_exit([&] {
  14519. svr.stop();
  14520. t.join();
  14521. });
  14522. svr.wait_until_ready();
  14523. SSLClient cli(HOST, port);
  14524. cli.enable_server_hostname_verification(false);
  14525. auto calls = 0;
  14526. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14527. calls++;
  14528. return true;
  14529. });
  14530. // cert.pem is not trusted
  14531. auto res = cli.Get("/test");
  14532. ASSERT_FALSE(res);
  14533. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14534. EXPECT_GT(calls, 0);
  14535. cli.enable_server_certificate_verification(false);
  14536. res = cli.Get("/test");
  14537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14538. EXPECT_EQ("ok", res->body);
  14539. }
  14540. // A verifier belongs to the client that set it, not to the thread that set it.
  14541. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14542. using namespace httplib::tls;
  14543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14544. ASSERT_TRUE(svr.is_valid());
  14545. svr.Get("/test", [](const Request &, Response &res) {
  14546. res.set_content("ok", "text/plain");
  14547. });
  14548. auto port = svr.bind_to_any_port(HOST);
  14549. thread t([&]() { svr.listen_after_bind(); });
  14550. auto se = detail::scope_exit([&] {
  14551. svr.stop();
  14552. t.join();
  14553. });
  14554. svr.wait_until_ready();
  14555. auto rejecting_calls = 0;
  14556. SSLClient rejecting(HOST, port);
  14557. rejecting.enable_server_certificate_verification(false);
  14558. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14559. rejecting_calls++;
  14560. return false;
  14561. });
  14562. auto accepting_calls = 0;
  14563. SSLClient accepting(HOST, port);
  14564. accepting.enable_server_certificate_verification(false);
  14565. // Set on another thread than the requests below.
  14566. thread([&]() {
  14567. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14568. accepting_calls++;
  14569. return true;
  14570. });
  14571. }).join();
  14572. // Requested on another thread than the verifier was set on.
  14573. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14574. EXPECT_GT(rejecting_calls, 0);
  14575. auto res = accepting.Get("/test");
  14576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14577. EXPECT_GT(accepting_calls, 0);
  14578. }
  14579. // A verifier replaced while a handshake runs it lives until it returns.
  14580. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. auto port = svr.bind_to_any_port(HOST);
  14588. thread t([&]() { svr.listen_after_bind(); });
  14589. auto se = detail::scope_exit([&] {
  14590. svr.stop();
  14591. t.join();
  14592. });
  14593. svr.wait_until_ready();
  14594. SSLClient cli(HOST, port);
  14595. cli.enable_server_certificate_verification(false);
  14596. std::promise<void> entered;
  14597. std::promise<void> replaced;
  14598. auto replaced_future = replaced.get_future();
  14599. auto first_call = true;
  14600. // Long enough to live on the heap
  14601. std::string expected(64, 'v');
  14602. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14603. if (first_call) {
  14604. first_call = false;
  14605. entered.set_value();
  14606. replaced_future.wait();
  14607. }
  14608. return expected == std::string(64, 'v');
  14609. });
  14610. thread request([&]() {
  14611. auto res = cli.Get("/test");
  14612. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14613. });
  14614. entered.get_future().wait();
  14615. cli.set_server_certificate_verifier(
  14616. [](const VerifyContext &) { return true; });
  14617. replaced.set_value();
  14618. request.join();
  14619. }
  14620. // VerifyContext::session is the same handle the other tls:: functions take.
  14621. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14622. using namespace httplib::tls;
  14623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14624. ASSERT_TRUE(svr.is_valid());
  14625. svr.Get("/test", [](const Request &, Response &res) {
  14626. res.set_content("ok", "text/plain");
  14627. });
  14628. auto port = svr.bind_to_any_port(HOST);
  14629. thread t([&]() { svr.listen_after_bind(); });
  14630. auto se = detail::scope_exit([&] {
  14631. svr.stop();
  14632. t.join();
  14633. });
  14634. svr.wait_until_ready();
  14635. SSLClient cli(HOST, port);
  14636. cli.enable_server_certificate_verification(false);
  14637. session_t verifier_session = nullptr;
  14638. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14639. verifier_session = ctx.session;
  14640. return true;
  14641. });
  14642. session_t session_verifier_session = nullptr;
  14643. cli.set_session_verifier([&](session_t session) {
  14644. session_verifier_session = session;
  14645. return SSLVerifierResponse::NoDecisionMade;
  14646. });
  14647. auto res = cli.Get("/test");
  14648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14649. EXPECT_NE(nullptr, verifier_session);
  14650. EXPECT_EQ(session_verifier_session, verifier_session);
  14651. }
  14652. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14653. using httplib::tls::TlsError;
  14654. // Test that verify_error_to_string returns empty for success
  14655. std::string success_str = TlsError::verify_error_to_string(0);
  14656. EXPECT_TRUE(success_str.empty());
  14657. // Test that verify_error_to_string returns non-empty for error codes
  14658. // Using a common error code (certificate expired)
  14659. std::string error_str =
  14660. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14661. EXPECT_FALSE(error_str.empty());
  14662. }
  14663. TEST(SessionVerifierTest, CertificateAccepted) {
  14664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14665. ASSERT_TRUE(svr.is_valid());
  14666. svr.Get("/test", [](const Request &, Response &res) {
  14667. res.set_content("ok", "text/plain");
  14668. });
  14669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14670. auto se = detail::scope_exit([&] {
  14671. svr.stop();
  14672. t.join();
  14673. });
  14674. svr.wait_until_ready();
  14675. SSLClient cli(HOST, PORT);
  14676. cli.enable_server_certificate_verification(false);
  14677. cli.set_connection_timeout(30);
  14678. bool callback_called = false;
  14679. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14680. EXPECT_NE(session, nullptr);
  14681. callback_called = true;
  14682. return SSLVerifierResponse::CertificateAccepted;
  14683. });
  14684. auto res = cli.Get("/test");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ(200, res->status);
  14687. EXPECT_TRUE(callback_called);
  14688. }
  14689. TEST(SessionVerifierTest, CertificateRejected) {
  14690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14691. ASSERT_TRUE(svr.is_valid());
  14692. svr.Get("/test", [](const Request &, Response &res) {
  14693. res.set_content("ok", "text/plain");
  14694. });
  14695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14696. auto se = detail::scope_exit([&] {
  14697. svr.stop();
  14698. t.join();
  14699. });
  14700. svr.wait_until_ready();
  14701. SSLClient cli(HOST, PORT);
  14702. cli.enable_server_certificate_verification(false);
  14703. cli.set_connection_timeout(30);
  14704. bool callback_called = false;
  14705. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14706. EXPECT_NE(session, nullptr);
  14707. callback_called = true;
  14708. return SSLVerifierResponse::CertificateRejected;
  14709. });
  14710. auto res = cli.Get("/test");
  14711. EXPECT_FALSE(res);
  14712. EXPECT_TRUE(callback_called);
  14713. }
  14714. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14716. ASSERT_TRUE(svr.is_valid());
  14717. svr.Get("/test", [](const Request &, Response &res) {
  14718. res.set_content("ok", "text/plain");
  14719. });
  14720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14721. auto se = detail::scope_exit([&] {
  14722. svr.stop();
  14723. t.join();
  14724. });
  14725. svr.wait_until_ready();
  14726. // NoDecisionMade with verification disabled should succeed (no default check)
  14727. SSLClient cli(HOST, PORT);
  14728. cli.enable_server_certificate_verification(false);
  14729. cli.set_connection_timeout(30);
  14730. bool callback_called = false;
  14731. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14732. EXPECT_NE(session, nullptr);
  14733. callback_called = true;
  14734. return SSLVerifierResponse::NoDecisionMade;
  14735. });
  14736. auto res = cli.Get("/test");
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(200, res->status);
  14739. EXPECT_TRUE(callback_called);
  14740. }
  14741. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14743. ASSERT_TRUE(svr.is_valid());
  14744. svr.Get("/test", [](const Request &, Response &res) {
  14745. res.set_content("ok", "text/plain");
  14746. });
  14747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14748. auto se = detail::scope_exit([&] {
  14749. svr.stop();
  14750. t.join();
  14751. });
  14752. svr.wait_until_ready();
  14753. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14754. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14755. // so we only check that the request fails, not whether the callback was
  14756. // called.
  14757. SSLClient cli(HOST, PORT);
  14758. cli.enable_server_certificate_verification(true);
  14759. cli.set_connection_timeout(30);
  14760. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14761. EXPECT_NE(session, nullptr);
  14762. return SSLVerifierResponse::NoDecisionMade;
  14763. });
  14764. auto res = cli.Get("/test");
  14765. EXPECT_FALSE(res);
  14766. }
  14767. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14768. // Test SSL server using PemMemory constructor with client CA certificates
  14769. // Read PEM files
  14770. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14771. read_file(SERVER_CERT_FILE, server_cert_pem);
  14772. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14773. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14774. // Create SSLServer with PemMemory constructor including client CA
  14775. SSLServer::PemMemory server_pem = {
  14776. server_cert_pem.c_str(),
  14777. server_cert_pem.size(),
  14778. server_key_pem.c_str(),
  14779. server_key_pem.size(),
  14780. client_ca_pem.c_str(),
  14781. client_ca_pem.size(),
  14782. nullptr // no password for server key
  14783. };
  14784. SSLServer svr(server_pem);
  14785. ASSERT_TRUE(svr.is_valid());
  14786. // No SSL error should be recorded for valid setup
  14787. EXPECT_EQ(0, svr.ssl_last_error());
  14788. // Set up server endpoints
  14789. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. // Start server in a thread
  14793. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14794. svr.wait_until_ready();
  14795. // Connect with client certificate (using constructor with paths)
  14796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14797. cli.enable_server_certificate_verification(false);
  14798. auto res = cli.Get("/test-pem-ca");
  14799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14800. EXPECT_EQ(200, res->status);
  14801. EXPECT_EQ("ok", res->body);
  14802. svr.stop();
  14803. server_thread.join();
  14804. }
  14805. #endif
  14806. #ifdef _WIN32
  14807. TEST(CleanupTest, WSACleanup) {
  14808. int ret = WSACleanup();
  14809. ASSERT_EQ(0, ret);
  14810. }
  14811. #endif
  14812. #ifndef CPPHTTPLIB_SSL_ENABLED
  14813. TEST(NoSSLSupport, SimpleInterface) {
  14814. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14815. }
  14816. #endif
  14817. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14818. TEST(InvalidScheme, SimpleInterface) {
  14819. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14820. }
  14821. #endif
  14822. TEST(NoScheme, SimpleInterface) {
  14823. Client cli("yahoo.com:80");
  14824. ASSERT_TRUE(cli.is_valid());
  14825. }
  14826. TEST(SendAPI, SimpleInterface_Online) {
  14827. Client cli("http://yahoo.com");
  14828. Request req;
  14829. req.method = "GET";
  14830. req.path = "/";
  14831. auto res = cli.send(req);
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14834. }
  14835. TEST(SendAPI, WithParamsInRequest) {
  14836. Server svr;
  14837. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14838. EXPECT_TRUE(req.has_param("test"));
  14839. EXPECT_EQ("test_value", req.get_param_value("test"));
  14840. });
  14841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14842. auto se = detail::scope_exit([&] {
  14843. svr.stop();
  14844. t.join();
  14845. ASSERT_FALSE(svr.is_running());
  14846. });
  14847. svr.wait_until_ready();
  14848. Client cli(HOST, PORT);
  14849. {
  14850. Request req;
  14851. req.method = "GET";
  14852. req.path = "/";
  14853. req.params.emplace("test", "test_value");
  14854. auto res = cli.send(req);
  14855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14856. }
  14857. {
  14858. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. }
  14861. }
  14862. TEST(ClientImplMethods, GetSocketTest) {
  14863. httplib::Server svr;
  14864. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14865. res.status = StatusCode::OK_200;
  14866. });
  14867. auto port = svr.bind_to_any_port("127.0.0.1");
  14868. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. thread.join();
  14872. ASSERT_FALSE(svr.is_running());
  14873. });
  14874. svr.wait_until_ready();
  14875. {
  14876. httplib::Client cli("127.0.0.1", port);
  14877. cli.set_keep_alive(true);
  14878. // Use the behavior of cpp-httplib of opening the connection
  14879. // only when the first request happens. If that changes,
  14880. // this test would be obsolete.
  14881. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14882. // This also implicitly tests the server. But other tests would fail much
  14883. // earlier than this one to be considered.
  14884. auto res = cli.Get("/");
  14885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14886. EXPECT_EQ(StatusCode::OK_200, res->status);
  14887. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14888. }
  14889. }
  14890. #ifdef CPPHTTPLIB_SSL_ENABLED
  14891. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14892. Client cli("http://yahoo.com");
  14893. auto res = cli.Get("/");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14896. cli.set_follow_location(true);
  14897. res = cli.Get("/");
  14898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14899. EXPECT_EQ(StatusCode::OK_200, res->status);
  14900. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14901. }
  14902. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14903. Client cli("https://yahoo.com");
  14904. auto res = cli.Get("/");
  14905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14906. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14907. cli.set_follow_location(true);
  14908. res = cli.Get("/");
  14909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14910. EXPECT_EQ(StatusCode::OK_200, res->status);
  14911. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14912. }
  14913. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14914. Client cli("https://yahoo.com");
  14915. auto res = cli.Get("/");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. ASSERT_FALSE(!res);
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. ASSERT_FALSE(res == nullptr);
  14920. ASSERT_TRUE(res != nullptr);
  14921. EXPECT_EQ(Error::Success, res.error());
  14922. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14923. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14925. cli.set_follow_location(true);
  14926. res = cli.Get("/");
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. EXPECT_EQ(Error::Success, res.error());
  14929. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14930. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14931. EXPECT_EQ(StatusCode::OK_200, res->status);
  14932. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14933. }
  14934. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14935. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14936. Client cli("https://cdnjs.cloudflare.com");
  14937. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14938. Headers{{"Accept-Encoding", "br"}});
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. EXPECT_EQ(287630U, res->body.size());
  14942. EXPECT_EQ("application/javascript; charset=utf-8",
  14943. res->get_header_value("Content-Type"));
  14944. }
  14945. #endif
  14946. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14947. #undef REDIR_HOST // Silence compiler warning
  14948. #define REDIR_HOST "https://httpbingo.org"
  14949. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14950. Client cli(REDIR_HOST);
  14951. cli.set_follow_location(true);
  14952. auto res =
  14953. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14955. EXPECT_EQ(StatusCode::OK_200, res->status);
  14956. }
  14957. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14958. Client cli(REDIR_HOST);
  14959. cli.set_follow_location(true);
  14960. Params params;
  14961. params.emplace("url", "http://example.com");
  14962. params.emplace("status_code", "302");
  14963. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14965. EXPECT_EQ(StatusCode::OK_200, res->status);
  14966. }
  14967. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14968. Client cli(REDIR_HOST);
  14969. cli.set_follow_location(true);
  14970. Params params;
  14971. params.emplace("url", "http://example.com");
  14972. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. TEST(HttpToHttpsRedirectTest, CertFile) {
  14977. auto ssl_port = PORT + 1;
  14978. Server svr;
  14979. ASSERT_TRUE(svr.is_valid());
  14980. svr.Get("/index", [&](const Request &, Response &res) {
  14981. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14982. "/index");
  14983. svr.stop();
  14984. });
  14985. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14986. ASSERT_TRUE(ssl_svr.is_valid());
  14987. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14988. res.set_content("test", "text/plain");
  14989. ssl_svr.stop();
  14990. });
  14991. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14992. thread t2 =
  14993. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14994. auto se = detail::scope_exit([&] {
  14995. t2.join();
  14996. t.join();
  14997. ASSERT_FALSE(svr.is_running());
  14998. });
  14999. svr.wait_until_ready();
  15000. ssl_svr.wait_until_ready();
  15001. Client cli("127.0.0.1", PORT);
  15002. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15003. cli.enable_server_certificate_verification(true);
  15004. cli.set_follow_location(true);
  15005. cli.set_connection_timeout(30);
  15006. auto res = cli.Get("/index");
  15007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15008. ASSERT_EQ(StatusCode::OK_200, res->status);
  15009. }
  15010. TEST(SSLClientRedirectTest, CertFile) {
  15011. auto ssl_port = PORT + 1;
  15012. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15013. ASSERT_TRUE(ssl_svr1.is_valid());
  15014. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15015. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15016. "/index");
  15017. ssl_svr1.stop();
  15018. });
  15019. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15020. ASSERT_TRUE(ssl_svr2.is_valid());
  15021. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15022. res.set_content("test", "text/plain");
  15023. ssl_svr2.stop();
  15024. });
  15025. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15026. thread t2 =
  15027. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15028. auto se = detail::scope_exit([&] {
  15029. t2.join();
  15030. t.join();
  15031. ASSERT_FALSE(ssl_svr1.is_running());
  15032. });
  15033. ssl_svr1.wait_until_ready();
  15034. ssl_svr2.wait_until_ready();
  15035. SSLClient cli("127.0.0.1", PORT);
  15036. std::string cert;
  15037. read_file(SERVER_CERT2_FILE, cert);
  15038. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15039. cli.enable_server_certificate_verification(true);
  15040. cli.set_follow_location(true);
  15041. cli.set_connection_timeout(30);
  15042. auto res = cli.Get("/index");
  15043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15044. ASSERT_EQ(StatusCode::OK_200, res->status);
  15045. }
  15046. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15047. // another port, so the client follows it with a new client.
  15048. static Result GetThroughTlsRedirectToDifferentPort(
  15049. const std::function<void(SSLClient &)> &setup,
  15050. const char *target_cert = SERVER_CERT2_FILE,
  15051. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15052. auto ssl_port = PORT + 1;
  15053. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15054. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15055. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15056. "/index");
  15057. });
  15058. SSLServer ssl_svr2(target_cert, target_key);
  15059. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15060. res.set_content("test", "text/plain");
  15061. });
  15062. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15063. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15064. auto se = detail::scope_exit([&] {
  15065. ssl_svr2.stop();
  15066. ssl_svr1.stop();
  15067. t2.join();
  15068. t.join();
  15069. });
  15070. ssl_svr1.wait_until_ready();
  15071. ssl_svr2.wait_until_ready();
  15072. SSLClient cli("127.0.0.1", PORT);
  15073. cli.set_follow_location(true);
  15074. cli.set_connection_timeout(30);
  15075. setup(cli);
  15076. return cli.Get("/index");
  15077. }
  15078. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15079. auto calls = 0;
  15080. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15081. cli.enable_server_certificate_verification(false);
  15082. // Accept the first server only.
  15083. cli.set_session_verifier([&](tls::session_t) {
  15084. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15085. : SSLVerifierResponse::CertificateRejected;
  15086. });
  15087. });
  15088. ASSERT_FALSE(res);
  15089. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15090. EXPECT_EQ(2, calls);
  15091. }
  15092. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15093. std::string pinned;
  15094. auto res = GetThroughTlsRedirectToDifferentPort(
  15095. [&](SSLClient &cli) {
  15096. cli.enable_server_certificate_verification(false);
  15097. // Pin the first certificate seen.
  15098. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15099. if (pinned.empty()) { pinned = ctx.serial(); }
  15100. return ctx.serial() == pinned;
  15101. });
  15102. },
  15103. // A certificate other than the first server's.
  15104. SERVER_CERT_FILE);
  15105. EXPECT_FALSE(res);
  15106. EXPECT_FALSE(pinned.empty());
  15107. }
  15108. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15109. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15110. std::string cert;
  15111. read_file(SERVER_CERT2_FILE, cert);
  15112. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15113. });
  15114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15115. EXPECT_EQ(StatusCode::OK_200, res->status);
  15116. }
  15117. // The target's certificate is signed by the root CA, which the first server's
  15118. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15119. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15120. auto res = GetThroughTlsRedirectToDifferentPort(
  15121. [](SSLClient &cli) {
  15122. std::string root_ca, cert;
  15123. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15124. read_file(SERVER_CERT2_FILE, cert);
  15125. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15126. cli.load_ca_cert_store(cert.data(), cert.size());
  15127. cli.enable_server_hostname_verification(false);
  15128. },
  15129. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. EXPECT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15134. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15135. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15136. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15137. auto res = GetThroughTlsRedirectToDifferentPort(
  15138. [](SSLClient &cli) {
  15139. std::string root_ca, cert;
  15140. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15141. read_file(SERVER_CERT2_FILE, cert);
  15142. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15143. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15144. cli.enable_server_hostname_verification(false);
  15145. },
  15146. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15147. ASSERT_FALSE(res);
  15148. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15149. }
  15150. #endif
  15151. #endif
  15152. #ifdef CPPHTTPLIB_SSL_ENABLED
  15153. // Test that set_ca_cert_store() skips system certs (consistent with
  15154. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15155. // should be trusted - system certs should NOT be loaded.
  15156. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15157. // Load a specific cert that is NOT a system CA cert
  15158. std::string cert;
  15159. read_file(SERVER_CERT2_FILE, cert);
  15160. SSLClient cli("google.com");
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. // This should FAIL because:
  15164. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15165. // 2. System certs should NOT be loaded when custom store is set
  15166. // If system certs WERE loaded, this would succeed
  15167. auto res = cli.Get("/");
  15168. ASSERT_FALSE(res);
  15169. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15170. }
  15171. // Same as above, but through the native store handle path. Regression test:
  15172. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15173. // merged system certs into the user-provided store.
  15174. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15175. std::string cert;
  15176. read_file(SERVER_CERT2_FILE, cert);
  15177. SSLClient cli("google.com");
  15178. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15179. cli.enable_server_certificate_verification(true);
  15180. auto res = cli.Get("/");
  15181. ASSERT_FALSE(res);
  15182. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15183. }
  15184. // A custom store set via the native handle must still verify a server whose
  15185. // cert it does contain.
  15186. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15187. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15188. ASSERT_TRUE(svr.is_valid());
  15189. svr.Get("/test", [&](const Request &, Response &res) {
  15190. res.set_content("test", "text/plain");
  15191. });
  15192. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15193. auto se = detail::scope_exit([&] {
  15194. svr.stop();
  15195. t.join();
  15196. ASSERT_FALSE(svr.is_running());
  15197. });
  15198. svr.wait_until_ready();
  15199. SSLClient cli("127.0.0.1", PORT);
  15200. std::string cert;
  15201. read_file(SERVER_CERT2_FILE, cert);
  15202. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15203. cli.enable_server_certificate_verification(true);
  15204. cli.set_connection_timeout(30);
  15205. auto res = cli.Get("/test");
  15206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15207. ASSERT_EQ(StatusCode::OK_200, res->status);
  15208. }
  15209. // CA certs loaded through the universal Client must be transferred to the
  15210. // client created internally for following an HTTPS redirect. Regression test:
  15211. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15212. // the CA data for redirect transfer.
  15213. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15214. auto ssl_port = PORT + 1;
  15215. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15216. ASSERT_TRUE(ssl_svr1.is_valid());
  15217. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15218. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15219. "/index");
  15220. });
  15221. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15222. ASSERT_TRUE(ssl_svr2.is_valid());
  15223. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15224. res.set_content("test", "text/plain");
  15225. });
  15226. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15227. thread t2 =
  15228. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15229. auto se = detail::scope_exit([&] {
  15230. ssl_svr2.stop();
  15231. ssl_svr1.stop();
  15232. t2.join();
  15233. t.join();
  15234. ASSERT_FALSE(ssl_svr1.is_running());
  15235. });
  15236. ssl_svr1.wait_until_ready();
  15237. ssl_svr2.wait_until_ready();
  15238. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15239. std::string cert;
  15240. read_file(SERVER_CERT2_FILE, cert);
  15241. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15242. cli.enable_server_certificate_verification(true);
  15243. cli.set_follow_location(true);
  15244. cli.set_connection_timeout(30);
  15245. auto res = cli.Get("/index");
  15246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15247. ASSERT_EQ(StatusCode::OK_200, res->status);
  15248. }
  15249. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15250. // so a host signed by a system CA verifies even though a custom CA is set
  15251. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15252. std::string cert;
  15253. read_file(SERVER_CERT2_FILE, cert);
  15254. SSLClient cli("google.com");
  15255. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15256. cli.enable_system_ca(true);
  15257. cli.enable_server_certificate_verification(true);
  15258. auto res = cli.Get("/");
  15259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15260. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15261. }
  15262. // The custom CA remains effective when combined with the system CA
  15263. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15265. ASSERT_TRUE(svr.is_valid());
  15266. svr.Get("/test", [&](const Request &, Response &res) {
  15267. res.set_content("test", "text/plain");
  15268. });
  15269. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15270. auto se = detail::scope_exit([&] {
  15271. svr.stop();
  15272. t.join();
  15273. ASSERT_FALSE(svr.is_running());
  15274. });
  15275. svr.wait_until_ready();
  15276. SSLClient cli("127.0.0.1", PORT);
  15277. std::string cert;
  15278. read_file(SERVER_CERT2_FILE, cert);
  15279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15280. cli.enable_system_ca(true);
  15281. cli.enable_server_certificate_verification(true);
  15282. cli.set_connection_timeout(30);
  15283. auto res = cli.Get("/test");
  15284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15285. ASSERT_EQ(StatusCode::OK_200, res->status);
  15286. }
  15287. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15288. // skip chain verification entirely (only the certificate identity was
  15289. // checked), so a server presenting an untrusted certificate with a matching
  15290. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15291. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15292. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15293. ASSERT_TRUE(svr.is_valid());
  15294. svr.Get("/test", [&](const Request &, Response &res) {
  15295. res.set_content("test", "text/plain");
  15296. });
  15297. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. t.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. });
  15303. svr.wait_until_ready();
  15304. SSLClient cli("127.0.0.1", PORT);
  15305. std::string cert;
  15306. // A trusted CA that did not sign the server certificate. The server cert
  15307. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15308. // this connection.
  15309. read_file(CLIENT_CA_CERT_FILE, cert);
  15310. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15311. cli.enable_server_certificate_verification(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/test");
  15314. ASSERT_FALSE(res);
  15315. }
  15316. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15317. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15318. // CA that failed to come through fails verification instead of trusting them.
  15319. // (wolfSSL does not list the system CAs it loaded.)
  15320. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15321. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15322. ASSERT_TRUE(svr.is_valid());
  15323. auto port = svr.bind_to_any_port("127.0.0.1");
  15324. ASSERT_LT(0, port);
  15325. thread t = thread([&] { svr.listen_after_bind(); });
  15326. auto se = detail::scope_exit([&] {
  15327. svr.stop();
  15328. t.join();
  15329. ASSERT_FALSE(svr.is_running());
  15330. });
  15331. svr.wait_until_ready();
  15332. // The CAs a client trusts once its first request has loaded them
  15333. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15334. Client cli("https://127.0.0.1:" + std::to_string(port));
  15335. setup(cli);
  15336. cli.Get("/");
  15337. return tls::get_ca_names(cli.tls_context()).size();
  15338. };
  15339. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15340. EXPECT_EQ(0u,
  15341. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15342. }
  15343. #endif
  15344. // A TLS setting changed between requests applies to the next one, not just to
  15345. // the next connection
  15346. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15347. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15348. ASSERT_TRUE(svr.is_valid());
  15349. svr.Get("/", [](const Request &req, Response &res) {
  15350. res.set_content(std::to_string(req.remote_port), "text/plain");
  15351. });
  15352. auto port = svr.bind_to_any_port("127.0.0.1");
  15353. ASSERT_LT(0, port);
  15354. thread t = thread([&] { svr.listen_after_bind(); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. });
  15360. svr.wait_until_ready();
  15361. SSLClient cli("127.0.0.1", port);
  15362. cli.set_keep_alive(true);
  15363. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15364. cli.enable_server_certificate_verification(false);
  15365. // The port the request went out from, so a new one means a new connection
  15366. auto client_port = [&] {
  15367. auto res = cli.Get("/");
  15368. return res ? res->body : std::string();
  15369. };
  15370. auto last = client_port();
  15371. ASSERT_FALSE(last.empty());
  15372. // Setting a value it already has keeps the connection
  15373. cli.enable_server_certificate_verification(false);
  15374. cli.enable_server_hostname_verification(true);
  15375. EXPECT_EQ(last, client_port());
  15376. cli.enable_server_certificate_verification(true);
  15377. auto res = cli.Get("/");
  15378. EXPECT_FALSE(res);
  15379. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15380. std::string ca;
  15381. read_file(SERVER_CERT2_FILE, ca);
  15382. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15383. last = client_port();
  15384. ASSERT_FALSE(last.empty());
  15385. std::vector<std::function<void()>> setters = {
  15386. [&] { cli.enable_server_hostname_verification(false); },
  15387. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15388. [&] {
  15389. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15390. },
  15391. [&] {
  15392. cli.set_server_certificate_verifier(
  15393. [](const tls::VerifyContext &) { return true; });
  15394. },
  15395. [&] {
  15396. cli.set_session_verifier(
  15397. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15398. },
  15399. };
  15400. for (const auto &setter : setters) {
  15401. setter();
  15402. auto next = client_port();
  15403. ASSERT_FALSE(next.empty());
  15404. EXPECT_NE(last, next);
  15405. last = next;
  15406. }
  15407. cli.set_session_verifier(
  15408. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15409. auto handle = cli.open_stream("GET", "/");
  15410. EXPECT_FALSE(handle.is_valid());
  15411. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15412. }
  15413. // A PEM given to create_ca_store() needs no NUL after it
  15414. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15415. std::string pem;
  15416. read_file(SERVER_CERT2_FILE, pem);
  15417. auto buf = pem + "X";
  15418. auto store = tls::create_ca_store(buf.data(), pem.size());
  15419. EXPECT_TRUE(store != nullptr);
  15420. SSLClient cli("localhost");
  15421. cli.set_ca_cert_store(store);
  15422. }
  15423. // enable_system_ca(false) prevents system CA loading entirely
  15424. TEST(SSLClientTest, DisableSystemCa_Online) {
  15425. SSLClient cli("google.com");
  15426. cli.enable_system_ca(false);
  15427. cli.enable_server_certificate_verification(true);
  15428. auto res = cli.Get("/");
  15429. ASSERT_FALSE(res);
  15430. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15431. // itself when the CA chain is empty
  15432. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15433. res.error() == Error::SSLConnection);
  15434. }
  15435. // The universal Client forwards enable_system_ca()
  15436. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15437. std::string cert;
  15438. read_file(SERVER_CERT2_FILE, cert);
  15439. Client cli("https://google.com");
  15440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15441. cli.enable_system_ca(true);
  15442. cli.enable_server_certificate_verification(true);
  15443. auto res = cli.Get("/");
  15444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15445. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15446. }
  15447. // The system CA policy must carry over to the client created internally for
  15448. // following a cross-host HTTPS redirect
  15449. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15450. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15451. ASSERT_TRUE(svr.is_valid());
  15452. svr.Get("/index", [&](const Request &, Response &res) {
  15453. res.set_redirect("https://www.google.com/");
  15454. });
  15455. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15456. auto se = detail::scope_exit([&] {
  15457. svr.stop();
  15458. t.join();
  15459. ASSERT_FALSE(svr.is_running());
  15460. });
  15461. svr.wait_until_ready();
  15462. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15463. std::string cert;
  15464. read_file(SERVER_CERT2_FILE, cert);
  15465. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15466. cli.enable_system_ca(true);
  15467. cli.enable_server_certificate_verification(true);
  15468. cli.set_follow_location(true);
  15469. cli.set_connection_timeout(30);
  15470. // Receiving any response proves the redirect client completed the TLS
  15471. // handshake with a system-CA-signed host
  15472. auto res = cli.Get("/index");
  15473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15474. }
  15475. TEST(MultipartFormDataTest, LargeData) {
  15476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15477. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15478. const ContentReader &content_reader) {
  15479. if (req.is_multipart_form_data()) {
  15480. std::vector<FormData> items;
  15481. content_reader(
  15482. [&](const FormData &file) {
  15483. items.push_back(file);
  15484. return true;
  15485. },
  15486. [&](const char *data, size_t data_length) {
  15487. items.back().content.append(data, data_length);
  15488. return true;
  15489. });
  15490. EXPECT_TRUE(std::string(items[0].name) == "document");
  15491. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15492. EXPECT_TRUE(items[0].filename == "2MB_data");
  15493. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15494. EXPECT_TRUE(items[1].name == "hello");
  15495. EXPECT_TRUE(items[1].content == "world");
  15496. EXPECT_TRUE(items[1].filename == "");
  15497. EXPECT_TRUE(items[1].content_type == "");
  15498. } else {
  15499. std::string body;
  15500. content_reader([&](const char *data, size_t data_length) {
  15501. body.append(data, data_length);
  15502. return true;
  15503. });
  15504. }
  15505. });
  15506. auto port = svr.bind_to_any_port(HOST);
  15507. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15508. auto se = detail::scope_exit([&] {
  15509. svr.stop();
  15510. t.join();
  15511. ASSERT_FALSE(svr.is_running());
  15512. });
  15513. svr.wait_until_ready();
  15514. {
  15515. std::string data(1024 * 1024 * 2, '.');
  15516. std::stringstream buffer;
  15517. buffer << data;
  15518. SSLClient cli(HOST, port);
  15519. cli.enable_server_certificate_verification(false);
  15520. UploadFormDataItems items{
  15521. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15522. {"hello", "world", "", ""},
  15523. };
  15524. auto res = cli.Post("/post", items);
  15525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15526. ASSERT_EQ(StatusCode::OK_200, res->status);
  15527. }
  15528. }
  15529. TEST(MultipartFormDataTest, DataProviderItems) {
  15530. std::random_device seed_gen;
  15531. std::mt19937 random(seed_gen());
  15532. std::string rand1;
  15533. rand1.resize(1000);
  15534. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15535. std::string rand2;
  15536. rand2.resize(3000);
  15537. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15539. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15540. const ContentReader &content_reader) {
  15541. ASSERT_FALSE(req.is_multipart_form_data());
  15542. std::string body;
  15543. content_reader([&](const char *data, size_t data_length) {
  15544. body.append(data, data_length);
  15545. return true;
  15546. });
  15547. EXPECT_EQ(body, "");
  15548. });
  15549. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15550. const ContentReader &content_reader) {
  15551. ASSERT_TRUE(req.is_multipart_form_data());
  15552. std::vector<FormData> items;
  15553. content_reader(
  15554. [&](const FormData &file) {
  15555. items.push_back(file);
  15556. return true;
  15557. },
  15558. [&](const char *data, size_t data_length) {
  15559. items.back().content.append(data, data_length);
  15560. return true;
  15561. });
  15562. ASSERT_TRUE(items.size() == 2);
  15563. EXPECT_EQ(std::string(items[0].name), "name1");
  15564. EXPECT_EQ(items[0].content, "Testing123");
  15565. EXPECT_EQ(items[0].filename, "filename1");
  15566. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15567. EXPECT_EQ(items[1].name, "name2");
  15568. EXPECT_EQ(items[1].content, "Testing456");
  15569. EXPECT_EQ(items[1].filename, "");
  15570. EXPECT_EQ(items[1].content_type, "");
  15571. });
  15572. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15573. const ContentReader &content_reader) {
  15574. ASSERT_TRUE(req.is_multipart_form_data());
  15575. std::vector<FormData> items;
  15576. content_reader(
  15577. [&](const FormData &file) {
  15578. items.push_back(file);
  15579. return true;
  15580. },
  15581. [&](const char *data, size_t data_length) {
  15582. items.back().content.append(data, data_length);
  15583. return true;
  15584. });
  15585. ASSERT_TRUE(items.size() == 2);
  15586. EXPECT_EQ(items[0].name, "name3");
  15587. EXPECT_EQ(items[0].content, rand1);
  15588. EXPECT_EQ(items[0].filename, "filename3");
  15589. EXPECT_EQ(items[0].content_type, "");
  15590. EXPECT_EQ(items[1].name, "name4");
  15591. EXPECT_EQ(items[1].content, rand2);
  15592. EXPECT_EQ(items[1].filename, "filename4");
  15593. EXPECT_EQ(items[1].content_type, "");
  15594. });
  15595. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15596. const ContentReader &content_reader) {
  15597. ASSERT_TRUE(req.is_multipart_form_data());
  15598. std::vector<FormData> items;
  15599. content_reader(
  15600. [&](const FormData &file) {
  15601. items.push_back(file);
  15602. return true;
  15603. },
  15604. [&](const char *data, size_t data_length) {
  15605. items.back().content.append(data, data_length);
  15606. return true;
  15607. });
  15608. ASSERT_TRUE(items.size() == 4);
  15609. EXPECT_EQ(std::string(items[0].name), "name1");
  15610. EXPECT_EQ(items[0].content, "Testing123");
  15611. EXPECT_EQ(items[0].filename, "filename1");
  15612. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15613. EXPECT_EQ(items[1].name, "name2");
  15614. EXPECT_EQ(items[1].content, "Testing456");
  15615. EXPECT_EQ(items[1].filename, "");
  15616. EXPECT_EQ(items[1].content_type, "");
  15617. EXPECT_EQ(items[2].name, "name3");
  15618. EXPECT_EQ(items[2].content, rand1);
  15619. EXPECT_EQ(items[2].filename, "filename3");
  15620. EXPECT_EQ(items[2].content_type, "");
  15621. EXPECT_EQ(items[3].name, "name4");
  15622. EXPECT_EQ(items[3].content, rand2);
  15623. EXPECT_EQ(items[3].filename, "filename4");
  15624. EXPECT_EQ(items[3].content_type, "");
  15625. });
  15626. auto port = svr.bind_to_any_port("localhost");
  15627. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. t.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. {
  15635. SSLClient cli("localhost", port);
  15636. cli.enable_server_certificate_verification(false);
  15637. UploadFormDataItems items{
  15638. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15639. {"name2", "Testing456", "", ""}, // not a file
  15640. };
  15641. {
  15642. auto res = cli.Post("/post-none", {}, {}, {});
  15643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15644. ASSERT_EQ(StatusCode::OK_200, res->status);
  15645. }
  15646. FormDataProviderItems providers;
  15647. {
  15648. auto res =
  15649. cli.Post("/post-items", {}, items, providers); // empty providers
  15650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15651. ASSERT_EQ(StatusCode::OK_200, res->status);
  15652. }
  15653. providers.push_back({"name3",
  15654. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15655. // test the offset is given correctly at each step
  15656. if (!offset)
  15657. sink.os.write(rand1.data(), 30);
  15658. else if (offset == 30)
  15659. sink.os.write(rand1.data() + 30, 300);
  15660. else if (offset == 330)
  15661. sink.os.write(rand1.data() + 330, 670);
  15662. else if (offset == rand1.size())
  15663. sink.done();
  15664. return true;
  15665. },
  15666. "filename3",
  15667. {}});
  15668. providers.push_back({"name4",
  15669. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15670. // test the offset is given correctly at each step
  15671. if (!offset)
  15672. sink.os.write(rand2.data(), 2000);
  15673. else if (offset == 2000)
  15674. sink.os.write(rand2.data() + 2000, 1);
  15675. else if (offset == 2001)
  15676. sink.os.write(rand2.data() + 2001, 999);
  15677. else if (offset == rand2.size())
  15678. sink.done();
  15679. return true;
  15680. },
  15681. "filename4",
  15682. {}});
  15683. {
  15684. auto res = cli.Post("/post-providers", {}, {}, providers);
  15685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15686. ASSERT_EQ(StatusCode::OK_200, res->status);
  15687. }
  15688. {
  15689. auto res = cli.Post("/post-both", {}, items, providers);
  15690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15691. ASSERT_EQ(StatusCode::OK_200, res->status);
  15692. }
  15693. }
  15694. }
  15695. TEST(MultipartFormDataTest, BadHeader) {
  15696. Server svr;
  15697. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15698. res.set_content("ok", "text/plain");
  15699. });
  15700. thread t = thread([&] { svr.listen(HOST, PORT); });
  15701. auto se = detail::scope_exit([&] {
  15702. svr.stop();
  15703. t.join();
  15704. ASSERT_FALSE(svr.is_running());
  15705. });
  15706. svr.wait_until_ready();
  15707. const std::string body =
  15708. "This is the preamble. It is to be ignored, though it\r\n"
  15709. "is a handy place for composition agents to include an\r\n"
  15710. "explanatory note to non-MIME conformant readers.\r\n"
  15711. "\r\n"
  15712. "\r\n"
  15713. "--simple boundary\r\n"
  15714. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15715. ": BAD...\r\n"
  15716. "\r\n"
  15717. "value1\r\n"
  15718. "--simple boundary\r\n"
  15719. "Content-Disposition: form-data; name=\"field2\"; "
  15720. "filename=\"example.txt\"\r\n"
  15721. "\r\n"
  15722. "value2\r\n"
  15723. "--simple boundary--\r\n"
  15724. "This is the epilogue. It is also to be ignored.\r\n";
  15725. std::string content_type =
  15726. R"(multipart/form-data; boundary="simple boundary")";
  15727. Client cli(HOST, PORT);
  15728. auto res = cli.Post("/post", body, content_type.c_str());
  15729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15731. }
  15732. TEST(MultipartFormDataTest, WithPreamble) {
  15733. Server svr;
  15734. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. thread t = thread([&] { svr.listen(HOST, PORT); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. t.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. const std::string body =
  15745. "This is the preamble. It is to be ignored, though it\r\n"
  15746. "is a handy place for composition agents to include an\r\n"
  15747. "explanatory note to non-MIME conformant readers.\r\n"
  15748. "\r\n"
  15749. "\r\n"
  15750. "--simple boundary\r\n"
  15751. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15752. "\r\n"
  15753. "value1\r\n"
  15754. "--simple boundary\r\n"
  15755. "Content-Disposition: form-data; name=\"field2\"; "
  15756. "filename=\"example.txt\"\r\n"
  15757. "\r\n"
  15758. "value2\r\n"
  15759. "--simple boundary--\r\n"
  15760. "This is the epilogue. It is also to be ignored.\r\n";
  15761. std::string content_type =
  15762. R"(multipart/form-data; boundary="simple boundary")";
  15763. Client cli(HOST, PORT);
  15764. auto res = cli.Post("/post", body, content_type.c_str());
  15765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15766. EXPECT_EQ(StatusCode::OK_200, res->status);
  15767. }
  15768. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15770. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15771. const ContentReader &content_reader) {
  15772. if (req.is_multipart_form_data()) {
  15773. std::vector<FormData> items;
  15774. content_reader(
  15775. [&](const FormData &file) {
  15776. items.push_back(file);
  15777. return true;
  15778. },
  15779. [&](const char *data, size_t data_length) {
  15780. items.back().content.append(data, data_length);
  15781. return true;
  15782. });
  15783. EXPECT_TRUE(std::string(items[0].name) == "document");
  15784. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15785. EXPECT_TRUE(items[0].filename == "2MB_data");
  15786. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15787. EXPECT_TRUE(items[1].name == "hello");
  15788. EXPECT_TRUE(items[1].content == "world");
  15789. EXPECT_TRUE(items[1].filename == "");
  15790. EXPECT_TRUE(items[1].content_type == "");
  15791. } else {
  15792. std::string body;
  15793. content_reader([&](const char *data, size_t data_length) {
  15794. body.append(data, data_length);
  15795. return true;
  15796. });
  15797. }
  15798. });
  15799. auto port = svr.bind_to_any_port("localhost");
  15800. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. {
  15808. std::string data(1024 * 1024 * 2, '.');
  15809. std::stringstream buffer;
  15810. buffer << data;
  15811. SSLClient cli("localhost", port);
  15812. cli.enable_server_certificate_verification(false);
  15813. UploadFormDataItems items{
  15814. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15815. {"hello", "world", "", ""},
  15816. };
  15817. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15819. ASSERT_EQ(StatusCode::OK_200, res->status);
  15820. }
  15821. }
  15822. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15823. std::string data(1024 * 1024 * 2, '&');
  15824. std::stringstream buffer;
  15825. buffer << data;
  15826. Client cli("https://localhost:8080");
  15827. UploadFormDataItems items{
  15828. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15829. {"hello", "world", "", ""},
  15830. };
  15831. for (const char &c : " \t\r\n") {
  15832. auto res =
  15833. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15834. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15835. ASSERT_FALSE(res);
  15836. }
  15837. }
  15838. TEST(MultipartFormDataTest, PutFormData) {
  15839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15840. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15841. const ContentReader &content_reader) {
  15842. if (req.is_multipart_form_data()) {
  15843. std::vector<FormData> items;
  15844. content_reader(
  15845. [&](const FormData &file) {
  15846. items.push_back(file);
  15847. return true;
  15848. },
  15849. [&](const char *data, size_t data_length) {
  15850. items.back().content.append(data, data_length);
  15851. return true;
  15852. });
  15853. EXPECT_TRUE(std::string(items[0].name) == "document");
  15854. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15855. EXPECT_TRUE(items[0].filename == "2MB_data");
  15856. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15857. EXPECT_TRUE(items[1].name == "hello");
  15858. EXPECT_TRUE(items[1].content == "world");
  15859. EXPECT_TRUE(items[1].filename == "");
  15860. EXPECT_TRUE(items[1].content_type == "");
  15861. } else {
  15862. std::string body;
  15863. content_reader([&](const char *data, size_t data_length) {
  15864. body.append(data, data_length);
  15865. return true;
  15866. });
  15867. }
  15868. });
  15869. auto port = svr.bind_to_any_port("localhost");
  15870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15871. auto se = detail::scope_exit([&] {
  15872. svr.stop();
  15873. t.join();
  15874. ASSERT_FALSE(svr.is_running());
  15875. });
  15876. svr.wait_until_ready();
  15877. {
  15878. std::string data(1024 * 1024 * 2, '&');
  15879. std::stringstream buffer;
  15880. buffer << data;
  15881. SSLClient cli("localhost", port);
  15882. cli.enable_server_certificate_verification(false);
  15883. UploadFormDataItems items{
  15884. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15885. {"hello", "world", "", ""},
  15886. };
  15887. auto res = cli.Put("/put", items);
  15888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15889. ASSERT_EQ(StatusCode::OK_200, res->status);
  15890. }
  15891. }
  15892. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15894. svr.Put("/put_customboundary",
  15895. [&](const Request &req, const Response & /*res*/,
  15896. const ContentReader &content_reader) {
  15897. if (req.is_multipart_form_data()) {
  15898. std::vector<FormData> items;
  15899. content_reader(
  15900. [&](const FormData &file) {
  15901. items.push_back(file);
  15902. return true;
  15903. },
  15904. [&](const char *data, size_t data_length) {
  15905. items.back().content.append(data, data_length);
  15906. return true;
  15907. });
  15908. EXPECT_TRUE(std::string(items[0].name) == "document");
  15909. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15910. EXPECT_TRUE(items[0].filename == "2MB_data");
  15911. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15912. EXPECT_TRUE(items[1].name == "hello");
  15913. EXPECT_TRUE(items[1].content == "world");
  15914. EXPECT_TRUE(items[1].filename == "");
  15915. EXPECT_TRUE(items[1].content_type == "");
  15916. } else {
  15917. std::string body;
  15918. content_reader([&](const char *data, size_t data_length) {
  15919. body.append(data, data_length);
  15920. return true;
  15921. });
  15922. }
  15923. });
  15924. auto port = svr.bind_to_any_port("localhost");
  15925. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15926. auto se = detail::scope_exit([&] {
  15927. svr.stop();
  15928. t.join();
  15929. ASSERT_FALSE(svr.is_running());
  15930. });
  15931. svr.wait_until_ready();
  15932. {
  15933. std::string data(1024 * 1024 * 2, '&');
  15934. std::stringstream buffer;
  15935. buffer << data;
  15936. SSLClient cli("localhost", port);
  15937. cli.enable_server_certificate_verification(false);
  15938. UploadFormDataItems items{
  15939. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15940. {"hello", "world", "", ""},
  15941. };
  15942. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15944. ASSERT_EQ(StatusCode::OK_200, res->status);
  15945. }
  15946. }
  15947. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15948. std::string data(1024 * 1024 * 2, '&');
  15949. std::stringstream buffer;
  15950. buffer << data;
  15951. Client cli("https://localhost:8080");
  15952. cli.enable_server_certificate_verification(false);
  15953. UploadFormDataItems items{
  15954. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15955. {"hello", "world", "", ""},
  15956. };
  15957. for (const char &c : " \t\r\n") {
  15958. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15959. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15960. ASSERT_FALSE(res);
  15961. }
  15962. }
  15963. TEST(MultipartFormDataTest, AlternateFilename) {
  15964. auto handled = false;
  15965. Server svr;
  15966. svr.Post("/test", [&](const Request &req, Response &res) {
  15967. ASSERT_EQ(2u, req.form.files.size());
  15968. ASSERT_EQ(1u, req.form.fields.size());
  15969. // Test files
  15970. const auto &file1 = req.form.get_file("file1");
  15971. ASSERT_EQ("file1", file1.name);
  15972. ASSERT_EQ("A.txt", file1.filename);
  15973. ASSERT_EQ("text/plain", file1.content_type);
  15974. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15975. const auto &file2 = req.form.get_file("file2");
  15976. ASSERT_EQ("file2", file2.name);
  15977. ASSERT_EQ("a.html", file2.filename);
  15978. ASSERT_EQ("text/html", file2.content_type);
  15979. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15980. file2.content);
  15981. // Test text field
  15982. const auto &text = req.form.get_field("text");
  15983. ASSERT_EQ("text default", text);
  15984. res.set_content("ok", "text/plain");
  15985. handled = true;
  15986. });
  15987. thread t = thread([&] { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. ASSERT_TRUE(handled);
  15993. });
  15994. svr.wait_until_ready();
  15995. auto req = "POST /test HTTP/1.1\r\n"
  15996. "Host: localhost\r\n"
  15997. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15998. "Content-Length: 399\r\n"
  15999. "\r\n"
  16000. "----------\r\n"
  16001. "Content-Disposition: form-data; name=\"text\"\r\n"
  16002. "\r\n"
  16003. "text default\r\n"
  16004. "----------\r\n"
  16005. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16006. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16007. "Content-Type: text/plain\r\n"
  16008. "\r\n"
  16009. "Content of a.txt.\r\n"
  16010. "\r\n"
  16011. "----------\r\n"
  16012. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16013. "\"a.html\"\r\n"
  16014. "Content-Type: text/html\r\n"
  16015. "\r\n"
  16016. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16017. "\r\n"
  16018. "------------\r\n";
  16019. ASSERT_TRUE(send_request(1, req));
  16020. }
  16021. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16022. auto handled = false;
  16023. Server svr;
  16024. svr.Post("/test", [&](const Request &req, Response &res) {
  16025. // Case-insensitive "utf-8''" prefix with a long value
  16026. const auto &file = req.form.get_file("file1");
  16027. ASSERT_EQ("file1", file.name);
  16028. // 8000 chars exercises both the Content-Disposition parser and the
  16029. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16030. // Prior to the fix, std::regex_match on this header would cause O(N)
  16031. // stack recursion in libstdc++, leading to SIGSEGV.
  16032. std::string expected_filename(8000, 'A');
  16033. ASSERT_EQ(expected_filename, file.filename);
  16034. res.set_content("ok", "text/plain");
  16035. handled = true;
  16036. });
  16037. thread t = thread([&] { svr.listen(HOST, PORT); });
  16038. auto se = detail::scope_exit([&] {
  16039. svr.stop();
  16040. t.join();
  16041. ASSERT_FALSE(svr.is_running());
  16042. ASSERT_TRUE(handled);
  16043. });
  16044. svr.wait_until_ready();
  16045. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16046. // Regression test for GHSA-qq6v-r583-3h69
  16047. std::string long_filename(8000, 'A');
  16048. std::string body = "----------\r\n"
  16049. "Content-Disposition: form-data; name=\"file1\"; "
  16050. "filename*=\"Utf-8''" +
  16051. long_filename +
  16052. "\"\r\n"
  16053. "\r\n"
  16054. "hello\r\n"
  16055. "------------\r\n";
  16056. auto req = "POST /test HTTP/1.1\r\n"
  16057. "Host: localhost\r\n"
  16058. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16059. "Content-Length: " +
  16060. std::to_string(body.size()) + "\r\n\r\n" + body;
  16061. ASSERT_TRUE(send_request(1, req));
  16062. }
  16063. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16064. auto handled = false;
  16065. Server svr;
  16066. svr.Post("/test", [&](const Request &req, Response &) {
  16067. ASSERT_EQ(2u, req.form.fields.size());
  16068. const auto &text1 = req.form.get_field("text1");
  16069. ASSERT_EQ("text1", text1);
  16070. const auto &text2 = req.form.get_field("text2");
  16071. ASSERT_EQ("text2", text2);
  16072. handled = true;
  16073. });
  16074. thread t = thread([&] { svr.listen(HOST, PORT); });
  16075. auto se = detail::scope_exit([&] {
  16076. svr.stop();
  16077. t.join();
  16078. ASSERT_FALSE(svr.is_running());
  16079. ASSERT_TRUE(handled);
  16080. });
  16081. svr.wait_until_ready();
  16082. auto req = "POST /test HTTP/1.1\r\n"
  16083. "Host: localhost\r\n"
  16084. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16085. "Content-Length: 146\r\n"
  16086. "\r\n----------\r\n"
  16087. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16088. "\r\n"
  16089. "text1"
  16090. "\r\n----------\r\n"
  16091. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16092. "\r\n"
  16093. "text2"
  16094. "\r\n------------";
  16095. std::string response;
  16096. ASSERT_TRUE(send_request(1, req, &response));
  16097. ASSERT_EQ("200", response.substr(9, 3));
  16098. }
  16099. TEST(MultipartFormDataTest, ContentLength) {
  16100. auto handled = false;
  16101. Server svr;
  16102. svr.Post("/test", [&](const Request &req, Response &) {
  16103. ASSERT_EQ(2u, req.form.fields.size());
  16104. const auto &text1 = req.form.get_field("text1");
  16105. ASSERT_EQ("text1", text1);
  16106. const auto &text2 = req.form.get_field("text2");
  16107. ASSERT_EQ("text2", text2);
  16108. handled = true;
  16109. });
  16110. thread t = thread([&] { svr.listen(HOST, PORT); });
  16111. auto se = detail::scope_exit([&] {
  16112. svr.stop();
  16113. t.join();
  16114. ASSERT_FALSE(svr.is_running());
  16115. ASSERT_TRUE(handled);
  16116. });
  16117. svr.wait_until_ready();
  16118. auto req = "POST /test HTTP/1.1\r\n"
  16119. "Host: localhost\r\n"
  16120. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16121. "Content-Length: 167\r\n"
  16122. "\r\n----------\r\n"
  16123. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16124. "Content-Length: 5\r\n"
  16125. "\r\n"
  16126. "text1"
  16127. "\r\n----------\r\n"
  16128. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16129. "\r\n"
  16130. "text2"
  16131. "\r\n------------\r\n";
  16132. std::string response;
  16133. ASSERT_TRUE(send_request(1, req, &response));
  16134. ASSERT_EQ("200", response.substr(9, 3));
  16135. }
  16136. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16137. auto handled = false;
  16138. Server svr;
  16139. svr.Post("/test", [&](const Request &req, Response &) {
  16140. ASSERT_EQ(2u, req.form.fields.size());
  16141. const auto &text1 = req.form.get_field("text1");
  16142. ASSERT_EQ("text1", text1);
  16143. // TODO: Add header access for text fields if needed
  16144. const auto &text2 = req.form.get_field("text2");
  16145. ASSERT_EQ("text2", text2);
  16146. // TODO: Header access for text fields needs to be implemented
  16147. // auto &headers = it->second.headers;
  16148. // ASSERT_EQ(3U, headers.size());
  16149. // auto custom_header = headers.find("x-whatever");
  16150. // ASSERT_TRUE(custom_header != headers.end());
  16151. // ASSERT_NE("customvalue", custom_header->second);
  16152. // ASSERT_EQ("CustomValue", custom_header->second);
  16153. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16154. handled = true;
  16155. });
  16156. thread t = thread([&] { svr.listen(HOST, PORT); });
  16157. auto se = detail::scope_exit([&] {
  16158. svr.stop();
  16159. t.join();
  16160. ASSERT_FALSE(svr.is_running());
  16161. ASSERT_TRUE(handled);
  16162. });
  16163. svr.wait_until_ready();
  16164. auto req = "POST /test HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16167. "Content-Length: 232\r\n"
  16168. "\r\n----------\r\n"
  16169. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16170. "Content-Length: 5\r\n"
  16171. "X-Test: 1\r\n"
  16172. "\r\n"
  16173. "text1"
  16174. "\r\n----------\r\n"
  16175. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16176. "Content-Type: text/plain\r\n"
  16177. "X-Whatever: CustomValue\r\n"
  16178. "\r\n"
  16179. "text2"
  16180. "\r\n------------\r\n"
  16181. "That should be disregarded. Not even read";
  16182. std::string response;
  16183. ASSERT_TRUE(send_request(1, req, &response));
  16184. ASSERT_EQ("200", response.substr(9, 3));
  16185. }
  16186. TEST(MultipartFormDataTest, LargeHeader) {
  16187. auto handled = false;
  16188. Server svr;
  16189. svr.Post("/test", [&](const Request &req, Response &) {
  16190. ASSERT_EQ(1u, req.form.fields.size());
  16191. const auto &text = req.form.get_field("name1");
  16192. ASSERT_EQ("text1", text);
  16193. handled = true;
  16194. });
  16195. thread t = thread([&] { svr.listen(HOST, PORT); });
  16196. auto se = detail::scope_exit([&] {
  16197. svr.stop();
  16198. t.join();
  16199. ASSERT_FALSE(svr.is_running());
  16200. ASSERT_TRUE(handled);
  16201. });
  16202. svr.wait_until_ready();
  16203. auto boundary = std::string("cpp-httplib-multipart-data");
  16204. std::string content = "--" + boundary +
  16205. "\r\n"
  16206. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16207. "\r\n"
  16208. "text1\r\n"
  16209. "--" +
  16210. boundary + "--\r\n";
  16211. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16212. "Host: localhost\r\n"
  16213. "Content-Type: multipart/form-data;boundary=" +
  16214. boundary +
  16215. "\r\n"
  16216. "Content-Length: " +
  16217. std::to_string(content.size()) +
  16218. "\r\n"
  16219. "Dummy-Header: ";
  16220. std::string header_suffix = "\r\n"
  16221. "\r\n";
  16222. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16223. size_t header_dummy_size =
  16224. read_buff_size -
  16225. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16226. auto header_dummy = std::string(header_dummy_size, '@');
  16227. auto req = header_prefix + header_dummy + header_suffix + content;
  16228. std::string response;
  16229. ASSERT_TRUE(send_request(1, req, &response));
  16230. ASSERT_EQ("200", response.substr(9, 3));
  16231. }
  16232. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16233. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16234. // (not chunked Transfer-Encoding) after the streaming refactor.
  16235. auto handled = false;
  16236. Server svr;
  16237. svr.Post("/upload", [&](const Request &req, Response &res) {
  16238. auto cl_it = req.headers.find("Content-Length");
  16239. EXPECT_TRUE(cl_it != req.headers.end());
  16240. auto te_it = req.headers.find("Transfer-Encoding");
  16241. EXPECT_TRUE(te_it == req.headers.end());
  16242. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16243. res.set_content("ok", "text/plain");
  16244. handled = true;
  16245. });
  16246. auto port = svr.bind_to_any_port(HOST);
  16247. auto t = thread([&] { svr.listen_after_bind(); });
  16248. auto se = detail::scope_exit([&] {
  16249. svr.stop();
  16250. t.join();
  16251. ASSERT_FALSE(svr.is_running());
  16252. ASSERT_TRUE(handled);
  16253. });
  16254. svr.wait_until_ready();
  16255. UploadFormDataItems items = {
  16256. {"field1", "hello", "", "text/plain"},
  16257. {"file1", "world", "test.txt", "application/octet-stream"},
  16258. };
  16259. Client cli(HOST, port);
  16260. auto res = cli.Post("/upload", {}, items);
  16261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16262. EXPECT_EQ(StatusCode::OK_200, res->status);
  16263. }
  16264. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16265. // Verify that make_multipart_content_provider coalesces many small segments
  16266. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16267. constexpr size_t kItemCount = 1000;
  16268. UploadFormDataItems items;
  16269. items.reserve(kItemCount);
  16270. for (size_t i = 0; i < kItemCount; i++) {
  16271. items.push_back(
  16272. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16273. }
  16274. const std::string boundary = "----test-boundary";
  16275. auto content_length = detail::get_multipart_content_length(items, boundary);
  16276. auto provider = detail::make_multipart_content_provider(items, boundary);
  16277. // Drive the provider the same way write_content_with_progress does
  16278. size_t write_count = 0;
  16279. size_t total_bytes = 0;
  16280. DataSink sink;
  16281. size_t offset = 0;
  16282. sink.write = [&](const char *d, size_t l) -> bool {
  16283. (void)d;
  16284. write_count++;
  16285. total_bytes += l;
  16286. offset += l;
  16287. return true;
  16288. };
  16289. sink.is_writable = []() -> bool { return true; };
  16290. while (offset < content_length) {
  16291. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16292. }
  16293. EXPECT_EQ(content_length, total_bytes);
  16294. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16295. // With buffering into 64KB blocks, write_count should be much smaller.
  16296. auto segment_count = 3 * kItemCount + 1;
  16297. EXPECT_LT(write_count, segment_count / 10);
  16298. }
  16299. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16300. // Integration test: send many UploadFormDataItems and verify the server
  16301. // receives all of them correctly (#2410).
  16302. constexpr size_t kItemCount = 500;
  16303. auto handled = false;
  16304. Server svr;
  16305. svr.Post("/upload", [&](const Request &req, Response &res) {
  16306. EXPECT_EQ(kItemCount, req.form.fields.size());
  16307. for (size_t i = 0; i < kItemCount; i++) {
  16308. auto key = "field" + std::to_string(i);
  16309. auto val = "value" + std::to_string(i);
  16310. auto it = req.form.fields.find(key);
  16311. if (it != req.form.fields.end()) {
  16312. EXPECT_EQ(val, it->second.content);
  16313. } else {
  16314. ADD_FAILURE() << "Missing field: " << key;
  16315. }
  16316. }
  16317. res.set_content("ok", "text/plain");
  16318. handled = true;
  16319. });
  16320. auto port = svr.bind_to_any_port(HOST);
  16321. auto t = thread([&] { svr.listen_after_bind(); });
  16322. auto se = detail::scope_exit([&] {
  16323. svr.stop();
  16324. t.join();
  16325. ASSERT_FALSE(svr.is_running());
  16326. ASSERT_TRUE(handled);
  16327. });
  16328. svr.wait_until_ready();
  16329. UploadFormDataItems items;
  16330. items.reserve(kItemCount);
  16331. for (size_t i = 0; i < kItemCount; i++) {
  16332. items.push_back(
  16333. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16334. }
  16335. Client cli(HOST, port);
  16336. auto res = cli.Post("/upload", items);
  16337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16338. EXPECT_EQ(StatusCode::OK_200, res->status);
  16339. }
  16340. TEST(MultipartFormDataTest, MakeFileProvider) {
  16341. // Verify make_file_provider sends a file's contents correctly.
  16342. const std::string file_content(4096, 'Z');
  16343. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16344. {
  16345. std::ofstream ofs(tmp_path, std::ios::binary);
  16346. ofs.write(file_content.data(),
  16347. static_cast<std::streamsize>(file_content.size()));
  16348. }
  16349. auto handled = false;
  16350. Server svr;
  16351. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16352. const ContentReader &content_reader) {
  16353. ASSERT_TRUE(req.is_multipart_form_data());
  16354. std::vector<FormData> items;
  16355. content_reader(
  16356. [&](const FormData &file) {
  16357. items.push_back(file);
  16358. return true;
  16359. },
  16360. [&](const char *data, size_t data_length) {
  16361. items.back().content.append(data, data_length);
  16362. return true;
  16363. });
  16364. ASSERT_EQ(1u, items.size());
  16365. EXPECT_EQ("myfile", items[0].name);
  16366. EXPECT_EQ("data.bin", items[0].filename);
  16367. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16368. EXPECT_EQ(file_content, items[0].content);
  16369. handled = true;
  16370. });
  16371. auto port = svr.bind_to_any_port(HOST);
  16372. auto t = thread([&] { svr.listen_after_bind(); });
  16373. auto se = detail::scope_exit([&] {
  16374. svr.stop();
  16375. t.join();
  16376. ASSERT_FALSE(svr.is_running());
  16377. ASSERT_TRUE(handled);
  16378. std::remove(tmp_path.c_str());
  16379. });
  16380. svr.wait_until_ready();
  16381. FormDataProviderItems providers;
  16382. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16383. "application/octet-stream"));
  16384. Client cli(HOST, port);
  16385. auto res = cli.Post("/upload", {}, {}, providers);
  16386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16387. EXPECT_EQ(StatusCode::OK_200, res->status);
  16388. }
  16389. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16390. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16391. // (100) headers is rejected with a 400 Bad Request response.
  16392. Server svr;
  16393. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16394. res.set_content("ok", "text/plain");
  16395. });
  16396. thread t = thread([&] { svr.listen(HOST, PORT); });
  16397. auto se = detail::scope_exit([&] {
  16398. svr.stop();
  16399. t.join();
  16400. ASSERT_FALSE(svr.is_running());
  16401. });
  16402. svr.wait_until_ready();
  16403. // Build a multipart part with 101 custom headers (exceeding
  16404. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16405. std::stringstream body;
  16406. body << "--simpleboundary\r\n"
  16407. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16408. for (int i = 0; i < 101; i++) {
  16409. body << "X-Custom-Header-" << i << ": value\r\n";
  16410. }
  16411. body << "\r\n"
  16412. << "value1\r\n"
  16413. << "--simpleboundary--\r\n";
  16414. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16415. Client cli(HOST, PORT);
  16416. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16419. }
  16420. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16421. // A body that never contains the declared boundary must not be accumulated
  16422. // while the parser waits for it. Buffering it would also make every read
  16423. // rescan everything seen so far, which is quadratic in the body size.
  16424. Server svr;
  16425. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16426. res.set_content("ok", "text/plain");
  16427. });
  16428. auto port = svr.bind_to_any_port(HOST);
  16429. thread t = thread([&] { svr.listen_after_bind(); });
  16430. auto se = detail::scope_exit([&] {
  16431. svr.stop();
  16432. t.join();
  16433. ASSERT_FALSE(svr.is_running());
  16434. });
  16435. svr.wait_until_ready();
  16436. Client cli(HOST, port);
  16437. cli.set_read_timeout(60, 0);
  16438. cli.set_write_timeout(60, 0);
  16439. // '-' is the worst case: it matches the first character of the boundary, so
  16440. // every position has to be checked against it.
  16441. auto post_dashes = [&](size_t size) {
  16442. const std::string body(size, '-');
  16443. auto start = std::chrono::steady_clock::now();
  16444. auto res =
  16445. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16446. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16447. std::chrono::steady_clock::now() - start)
  16448. .count();
  16449. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16450. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16451. return ms;
  16452. };
  16453. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16454. // Windows.
  16455. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16456. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16457. // Comparing the two sizes rather than checking an absolute duration keeps
  16458. // this meaningful across build types and CI load, both of which move the
  16459. // absolute numbers by more than an order of magnitude. Four times the bytes
  16460. // costs about four times the time when parsing is linear, and about sixteen
  16461. // times when the body is buffered and rescanned.
  16462. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16463. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16464. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16465. << "ms, which suggests the body is being buffered and rescanned";
  16466. }
  16467. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16468. // A boundary can only be followed by CRLF or by "--", so anything else is
  16469. // malformed no matter what comes next. The parser must say so right away
  16470. // instead of buffering the rest of the declared body.
  16471. Server svr;
  16472. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16473. res.set_content("ok", "text/plain");
  16474. });
  16475. auto port = svr.bind_to_any_port(HOST);
  16476. thread t = thread([&] { svr.listen_after_bind(); });
  16477. auto se = detail::scope_exit([&] {
  16478. svr.stop();
  16479. t.join();
  16480. ASSERT_FALSE(svr.is_running());
  16481. });
  16482. svr.wait_until_ready();
  16483. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16484. // buffers instead of failing would still be waiting for the remaining bytes.
  16485. const std::string body = "--zzzz\r\n"
  16486. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16487. "\r\n"
  16488. "text1"
  16489. "\r\n--zzzzXX";
  16490. const std::string req = "POST /post HTTP/1.1\r\n"
  16491. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16492. "Content-Length: 1048576\r\n"
  16493. "\r\n" +
  16494. body;
  16495. std::string response;
  16496. ASSERT_TRUE(send_request(3, req, &response, port));
  16497. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16498. EXPECT_EQ("400", response.substr(9, 3));
  16499. }
  16500. // Posts a multipart body split into two writes, so that the server sees the
  16501. // split at whatever offset the caller chose, and expects the single "text1"
  16502. // field to come through.
  16503. static void expect_split_multipart_ok(const std::string &body1,
  16504. const std::string &body2) {
  16505. auto handled = false;
  16506. Server svr;
  16507. svr.Post("/post", [&](const Request &req, Response &) {
  16508. EXPECT_EQ(1u, req.form.fields.size());
  16509. EXPECT_EQ("text1", req.form.get_field("text1"));
  16510. handled = true;
  16511. });
  16512. auto port = svr.bind_to_any_port(HOST);
  16513. thread t = thread([&] { svr.listen_after_bind(); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. ASSERT_TRUE(handled);
  16519. });
  16520. svr.wait_until_ready();
  16521. // "Connection: close" makes the server close once it has answered, so the
  16522. // response drain ends immediately instead of idling until the read timeout.
  16523. const std::string head =
  16524. "POST /post HTTP/1.1\r\n"
  16525. "Host: localhost\r\n"
  16526. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16527. "Connection: close\r\n"
  16528. "Content-Length: " +
  16529. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16530. std::string response;
  16531. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16532. ASSERT_GE(response.size(), 12u) << "no response";
  16533. EXPECT_EQ("200", response.substr(9, 3));
  16534. }
  16535. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16536. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16537. // ignored, including when it does not arrive in the same read as the
  16538. // close-delimiter itself.
  16539. expect_split_multipart_ok("--zzzz\r\n"
  16540. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16541. "\r\n"
  16542. "text1"
  16543. "\r\n--zzzz--",
  16544. "\r\nthis epilogue must be ignored\r\n");
  16545. }
  16546. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16547. // The initial boundary may be preceded by a preamble of any length and may
  16548. // straddle a read boundary. Discarding data while waiting for it must not
  16549. // throw away a partial boundary sitting at the end of the buffer.
  16550. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16551. "zz\r\n"
  16552. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16553. "\r\n"
  16554. "text1"
  16555. "\r\n--zzzz--\r\n");
  16556. }
  16557. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16558. // The received boundary was only checked for being non-empty, so it could be
  16559. // as long as a header is allowed to be. The parser scans the body for
  16560. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16561. // costs a nearly full comparison at nearly every position, making the
  16562. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16563. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16564. Server svr;
  16565. svr.Post("/post", [](const Request &req, Response &res) {
  16566. EXPECT_EQ(1u, req.form.fields.size());
  16567. EXPECT_EQ("text1", req.form.get_field("text1"));
  16568. res.set_content("ok", "text/plain");
  16569. });
  16570. auto port = svr.bind_to_any_port(HOST);
  16571. thread t = thread([&] { svr.listen_after_bind(); });
  16572. auto se = detail::scope_exit([&] {
  16573. svr.stop();
  16574. t.join();
  16575. ASSERT_FALSE(svr.is_running());
  16576. });
  16577. svr.wait_until_ready();
  16578. Client cli(HOST, port);
  16579. auto post_with_boundary_of_length = [&](size_t len) {
  16580. const std::string boundary(len, 'a');
  16581. const std::string body =
  16582. "--" + boundary +
  16583. "\r\n"
  16584. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16585. "\r\n"
  16586. "text1"
  16587. "\r\n--" +
  16588. boundary + "--\r\n";
  16589. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16590. };
  16591. auto res = post_with_boundary_of_length(70);
  16592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16593. EXPECT_EQ(StatusCode::OK_200, res->status);
  16594. res = post_with_boundary_of_length(71);
  16595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16596. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16597. }
  16598. TEST(MakeFileBodyTest, Basic) {
  16599. const std::string file_content(4096, 'Z');
  16600. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16601. {
  16602. std::ofstream ofs(tmp_path, std::ios::binary);
  16603. ofs.write(file_content.data(),
  16604. static_cast<std::streamsize>(file_content.size()));
  16605. }
  16606. auto handled = false;
  16607. Server svr;
  16608. svr.Post("/upload", [&](const Request &req, Response &res) {
  16609. EXPECT_EQ(file_content, req.body);
  16610. handled = true;
  16611. res.status = StatusCode::OK_200;
  16612. });
  16613. auto port = svr.bind_to_any_port(HOST);
  16614. auto t = thread([&] { svr.listen_after_bind(); });
  16615. auto se = detail::scope_exit([&] {
  16616. svr.stop();
  16617. t.join();
  16618. ASSERT_FALSE(svr.is_running());
  16619. ASSERT_TRUE(handled);
  16620. std::remove(tmp_path.c_str());
  16621. });
  16622. svr.wait_until_ready();
  16623. auto fb = make_file_body(tmp_path);
  16624. ASSERT_GT(fb.first, 0u);
  16625. Client cli(HOST, port);
  16626. auto res =
  16627. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16629. EXPECT_EQ(StatusCode::OK_200, res->status);
  16630. }
  16631. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16632. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16633. {
  16634. std::ofstream ofs(path, std::ios::binary);
  16635. const std::string content(100, 'A');
  16636. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16637. }
  16638. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16639. auto body = make_file_body(path);
  16640. ASSERT_EQ(100u, body.first);
  16641. ASSERT_TRUE(static_cast<bool>(body.second));
  16642. // Rewritten shorter after its length was measured - and, on a server, after
  16643. // that length has already gone out as Content-Length.
  16644. {
  16645. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16646. const std::string content(10, 'A');
  16647. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16648. }
  16649. std::string written;
  16650. DataSink sink;
  16651. sink.write = [&](const char *d, size_t l) {
  16652. written.append(d, l);
  16653. return true;
  16654. };
  16655. // The provider has to report failure. write_content_with_progress() advances
  16656. // its offset only by what was written, so a provider that returns true
  16657. // without completing the length it promised is called again straight away,
  16658. // and again.
  16659. EXPECT_FALSE(body.second(0, body.first, sink));
  16660. EXPECT_EQ(std::string(10, 'A'), written);
  16661. }
  16662. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16663. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16664. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16665. {
  16666. std::ofstream ofs(path, std::ios::binary);
  16667. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16668. }
  16669. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16670. auto body = make_file_body(path);
  16671. ASSERT_EQ(content.size(), body.first);
  16672. ASSERT_TRUE(static_cast<bool>(body.second));
  16673. std::string written;
  16674. DataSink sink;
  16675. sink.write = [&](const char *d, size_t l) {
  16676. written.append(d, l);
  16677. return true;
  16678. };
  16679. EXPECT_TRUE(body.second(0, body.first, sink));
  16680. EXPECT_EQ(content, written);
  16681. }
  16682. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16683. static constexpr unsigned int number_of_tasks{1000000};
  16684. std::atomic_uint count{0};
  16685. std::unique_ptr<TaskQueue> task_queue{
  16686. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16687. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16688. auto queued = task_queue->enqueue(
  16689. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16690. EXPECT_TRUE(queued);
  16691. }
  16692. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16693. task_queue->shutdown();
  16694. #else
  16695. EXPECT_NO_THROW(task_queue->shutdown());
  16696. #endif
  16697. EXPECT_EQ(number_of_tasks, count.load());
  16698. }
  16699. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16700. static constexpr unsigned int number_of_tasks{1000000};
  16701. static constexpr unsigned int qlimit{2};
  16702. unsigned int queued_count{0};
  16703. std::atomic_uint count{0};
  16704. std::unique_ptr<TaskQueue> task_queue{
  16705. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16706. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16707. if (task_queue->enqueue(
  16708. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16709. queued_count++;
  16710. }
  16711. }
  16712. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16713. task_queue->shutdown();
  16714. #else
  16715. EXPECT_NO_THROW(task_queue->shutdown());
  16716. #endif
  16717. EXPECT_EQ(queued_count, count.load());
  16718. EXPECT_TRUE(queued_count <= number_of_tasks);
  16719. EXPECT_TRUE(queued_count >= qlimit);
  16720. }
  16721. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16722. // Use a short idle timeout so a dynamic thread spawns, times out and
  16723. // exits during the test, and the pool keeps working afterwards.
  16724. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16725. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16726. /*idle_timeout_sec=*/1}};
  16727. std::atomic_uint count{0};
  16728. std::condition_variable cv;
  16729. std::mutex mtx;
  16730. bool release = false;
  16731. // Block the base thread so the second task spawns a dynamic thread.
  16732. EXPECT_TRUE(task_queue->enqueue([&] {
  16733. std::unique_lock<std::mutex> lock(mtx);
  16734. while (!release) {
  16735. cv.wait(lock);
  16736. }
  16737. count++;
  16738. }));
  16739. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16740. // Let the dynamic thread finish its task and exceed the idle timeout.
  16741. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16742. {
  16743. std::unique_lock<std::mutex> lock(mtx);
  16744. release = true;
  16745. }
  16746. cv.notify_all();
  16747. // The pool must still accept and run tasks after the dynamic thread exited.
  16748. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16749. task_queue->shutdown();
  16750. EXPECT_EQ(3u, count.load());
  16751. }
  16752. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16753. static constexpr size_t number_of_tasks{32};
  16754. std::unique_ptr<TaskQueue> task_queue{
  16755. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16756. // Let the base threads go idle so the burst below finds them waiting.
  16757. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16758. std::mutex mtx;
  16759. std::condition_variable cv;
  16760. size_t running = 0;
  16761. bool release = false;
  16762. for (size_t i = 0; i < number_of_tasks; i++) {
  16763. EXPECT_TRUE(task_queue->enqueue([&] {
  16764. std::unique_lock<std::mutex> lock(mtx);
  16765. running++;
  16766. cv.notify_all();
  16767. cv.wait(lock, [&] { return release; });
  16768. }));
  16769. }
  16770. {
  16771. std::unique_lock<std::mutex> lock(mtx);
  16772. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16773. [&] { return running == number_of_tasks; }));
  16774. release = true;
  16775. }
  16776. cv.notify_all();
  16777. task_queue->shutdown();
  16778. }
  16779. TEST(TaskQueueTest, MaxQueuedRequests) {
  16780. static constexpr unsigned int qlimit{3};
  16781. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16782. std::condition_variable sem_cv;
  16783. std::mutex sem_mtx;
  16784. int credits = 0;
  16785. bool queued;
  16786. /* Fill up the queue with tasks that will block until we give them credits to
  16787. * complete. */
  16788. for (unsigned int n = 0; n <= qlimit;) {
  16789. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16790. std::unique_lock<std::mutex> lock(sem_mtx);
  16791. while (credits <= 0) {
  16792. sem_cv.wait(lock);
  16793. }
  16794. /* Consume the credit and signal the test code if they are all gone. */
  16795. if (--credits == 0) { sem_cv.notify_one(); }
  16796. });
  16797. if (n < qlimit) {
  16798. /* The first qlimit enqueues must succeed. */
  16799. EXPECT_TRUE(queued);
  16800. } else {
  16801. /* The last one will succeed only when the worker thread
  16802. * starts and dequeues the first blocking task. Although
  16803. * not necessary for the correctness of this test, we sleep for
  16804. * a short while to avoid busy waiting. */
  16805. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16806. }
  16807. if (queued) { n++; }
  16808. }
  16809. /* Further enqueues must fail since the queue is full. */
  16810. for (auto i = 0; i < 4; i++) {
  16811. queued = task_queue->enqueue([] {});
  16812. EXPECT_FALSE(queued);
  16813. }
  16814. /* Give the credits to allow the previous tasks to complete. */
  16815. {
  16816. std::unique_lock<std::mutex> lock(sem_mtx);
  16817. credits += qlimit + 1;
  16818. }
  16819. sem_cv.notify_all();
  16820. /* Wait for all the credits to be consumed. */
  16821. {
  16822. std::unique_lock<std::mutex> lock(sem_mtx);
  16823. while (credits > 0) {
  16824. sem_cv.wait(lock);
  16825. }
  16826. }
  16827. /* Check that we are able again to enqueue at least qlimit tasks. */
  16828. for (unsigned int i = 0; i < qlimit; i++) {
  16829. queued = task_queue->enqueue([] {});
  16830. EXPECT_TRUE(queued);
  16831. }
  16832. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16833. task_queue->shutdown();
  16834. #else
  16835. EXPECT_NO_THROW(task_queue->shutdown());
  16836. #endif
  16837. }
  16838. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16839. Server svr;
  16840. std::string method;
  16841. std::string body;
  16842. auto has_content_length = false;
  16843. auto has_transfer_encoding = false;
  16844. std::atomic<int> bad_requests{0};
  16845. // Leftover body bytes get parsed as a malformed request and answered with
  16846. // 400
  16847. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16848. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16849. });
  16850. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16851. res.set_redirect("/down", StatusCode::SeeOther_303);
  16852. });
  16853. svr.Get("/down", [&](const Request &req, Response &res) {
  16854. method = req.method;
  16855. body = req.body;
  16856. has_content_length = req.has_header("Content-Length");
  16857. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16858. res.set_content("ok", "text/plain");
  16859. });
  16860. auto port = svr.bind_to_any_port(HOST);
  16861. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16862. auto se = detail::scope_exit([&] {
  16863. svr.stop();
  16864. thread.join();
  16865. ASSERT_FALSE(svr.is_running());
  16866. });
  16867. svr.wait_until_ready();
  16868. const std::string payload = "SECRET-BODY";
  16869. auto check = [&](Client &cli, const Result &res) {
  16870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16871. EXPECT_EQ(StatusCode::OK_200, res->status);
  16872. EXPECT_EQ("ok", res->body);
  16873. EXPECT_EQ("GET", method);
  16874. EXPECT_TRUE(body.empty());
  16875. EXPECT_FALSE(has_content_length);
  16876. EXPECT_FALSE(has_transfer_encoding);
  16877. // Nothing of the original body may be left on the connection
  16878. auto res2 = cli.Get("/down");
  16879. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16880. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16881. EXPECT_EQ("ok", res2->body);
  16882. EXPECT_EQ(0, bad_requests);
  16883. };
  16884. // With content length
  16885. {
  16886. Client cli(HOST, port);
  16887. cli.set_keep_alive(true);
  16888. cli.set_follow_location(true);
  16889. auto res = cli.Post(
  16890. "/up", payload.size(),
  16891. [&](size_t offset, size_t length, DataSink &sink) {
  16892. return sink.write(payload.data() + offset, length);
  16893. },
  16894. "text/plain");
  16895. check(cli, res);
  16896. }
  16897. // Without content length (chunked)
  16898. {
  16899. Client cli(HOST, port);
  16900. cli.set_keep_alive(true);
  16901. cli.set_follow_location(true);
  16902. auto res = cli.Post(
  16903. "/up",
  16904. [&](size_t /*offset*/, DataSink &sink) {
  16905. sink.write(payload.data(), payload.size());
  16906. sink.done();
  16907. return true;
  16908. },
  16909. "text/plain");
  16910. check(cli, res);
  16911. }
  16912. }
  16913. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16914. Server svr;
  16915. std::string target;
  16916. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16917. // Echo the still-encoded name back in the Location
  16918. const std::string prefix = "/start/";
  16919. res.status = StatusCode::Found_302;
  16920. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16921. });
  16922. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16923. target = req.target;
  16924. res.set_content("ok", "text/plain");
  16925. });
  16926. auto port = svr.bind_to_any_port(HOST);
  16927. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16928. auto se = detail::scope_exit([&] {
  16929. svr.stop();
  16930. thread.join();
  16931. ASSERT_FALSE(svr.is_running());
  16932. });
  16933. svr.wait_until_ready();
  16934. // Decoding the Location path would turn the first four into a path
  16935. // separator, a query delimiter, a fragment delimiter and a different
  16936. // percent-encoded octet. The rest must keep reaching the server as they are.
  16937. const std::vector<std::string> names = {
  16938. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16939. };
  16940. for (auto path_encode : {true, false}) {
  16941. Client cli(HOST, port);
  16942. cli.set_follow_location(true);
  16943. cli.set_path_encode(path_encode);
  16944. for (const auto &name : names) {
  16945. target.clear();
  16946. auto res = cli.Get("/start/" + name);
  16947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16948. EXPECT_EQ(StatusCode::OK_200, res->status);
  16949. EXPECT_EQ("/dest/" + name, target);
  16950. }
  16951. }
  16952. }
  16953. TEST(RedirectTest, NotModifiedIsReturned) {
  16954. Server svr;
  16955. svr.Get("/cached", [](const Request &, Response &res) {
  16956. res.status = StatusCode::NotModified_304;
  16957. });
  16958. auto port = svr.bind_to_any_port(HOST);
  16959. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16960. auto se = detail::scope_exit([&] {
  16961. svr.stop();
  16962. thread.join();
  16963. ASSERT_FALSE(svr.is_running());
  16964. });
  16965. svr.wait_until_ready();
  16966. Client cli(HOST, port);
  16967. cli.set_follow_location(true);
  16968. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16970. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16971. }
  16972. TEST(RedirectTest, NoLocationIsReturned) {
  16973. Server svr;
  16974. svr.Get("/no-location", [](const Request &, Response &res) {
  16975. res.status = StatusCode::Found_302;
  16976. res.set_content("no location", "text/plain");
  16977. });
  16978. auto port = svr.bind_to_any_port(HOST);
  16979. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16980. auto se = detail::scope_exit([&] {
  16981. svr.stop();
  16982. thread.join();
  16983. ASSERT_FALSE(svr.is_running());
  16984. });
  16985. svr.wait_until_ready();
  16986. Client cli(HOST, port);
  16987. cli.set_follow_location(true);
  16988. auto res = cli.Get("/no-location");
  16989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16990. EXPECT_EQ(StatusCode::Found_302, res->status);
  16991. EXPECT_EQ("no location", res->body);
  16992. // The callbacks see the body of the response that is returned
  16993. auto handler_called = false;
  16994. auto progress_called = false;
  16995. std::string body;
  16996. auto res2 = cli.Get(
  16997. "/no-location",
  16998. [&](const Response &) {
  16999. handler_called = true;
  17000. return true;
  17001. },
  17002. [&](const char *data, size_t data_length) {
  17003. body.append(data, data_length);
  17004. return true;
  17005. },
  17006. [&](size_t, size_t) {
  17007. progress_called = true;
  17008. return true;
  17009. });
  17010. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17011. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17012. EXPECT_TRUE(handler_called);
  17013. EXPECT_TRUE(progress_called);
  17014. EXPECT_EQ("no location", body);
  17015. }
  17016. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17017. Server svr;
  17018. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17019. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17020. });
  17021. svr.Get("/hello", [](const Request &req, Response &res) {
  17022. res.set_content(req.get_param_value("key"), "text/plain");
  17023. });
  17024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. {
  17032. Client cli(HOST, PORT);
  17033. cli.set_follow_location(true);
  17034. auto res = cli.Get("/");
  17035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17036. EXPECT_EQ(StatusCode::OK_200, res->status);
  17037. EXPECT_EQ("val&key2=val2", res->body);
  17038. }
  17039. }
  17040. #endif
  17041. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17042. Server svr;
  17043. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17044. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17045. });
  17046. svr.Get("/hello", [](const Request &req, Response &res) {
  17047. res.set_content(req.get_param_value("key"), "text/plain");
  17048. });
  17049. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17050. auto se = detail::scope_exit([&] {
  17051. svr.stop();
  17052. thread.join();
  17053. ASSERT_FALSE(svr.is_running());
  17054. });
  17055. svr.wait_until_ready();
  17056. {
  17057. Client cli(HOST, PORT);
  17058. cli.set_follow_location(true);
  17059. auto res = cli.Get("/");
  17060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17061. EXPECT_EQ(StatusCode::OK_200, res->status);
  17062. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17063. }
  17064. }
  17065. TEST(RedirectTest, RedirectWithPlusInPath) {
  17066. Server svr;
  17067. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17068. res.set_redirect("/a+b");
  17069. });
  17070. // Route pattern uses regex; escape + as \\+
  17071. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17072. res.set_content(req.path, "text/plain");
  17073. });
  17074. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17075. auto se = detail::scope_exit([&] {
  17076. svr.stop();
  17077. thread.join();
  17078. ASSERT_FALSE(svr.is_running());
  17079. });
  17080. svr.wait_until_ready();
  17081. {
  17082. Client cli(HOST, PORT);
  17083. cli.set_follow_location(true);
  17084. auto res = cli.Get("/");
  17085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17086. EXPECT_EQ(StatusCode::OK_200, res->status);
  17087. EXPECT_EQ("/a+b", res->body);
  17088. }
  17089. }
  17090. TEST(RedirectTest, ResolveRelativeLocation) {
  17091. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17092. const std::vector<std::pair<std::string, std::string>> cases = {
  17093. {"g", "/b/c/g"},
  17094. {"./g", "/b/c/g"},
  17095. {"g/", "/b/c/g/"},
  17096. {"?y", "/b/c/d;p?y"},
  17097. {"g?y", "/b/c/g?y"},
  17098. {"#s", "/b/c/d;p?q#s"},
  17099. {"g#s", "/b/c/g#s"},
  17100. {"g?y#s", "/b/c/g?y#s"},
  17101. {";x", "/b/c/;x"},
  17102. {"g;x", "/b/c/g;x"},
  17103. {".", "/b/c/"},
  17104. {"./", "/b/c/"},
  17105. {"..", "/b/"},
  17106. {"../", "/b/"},
  17107. {"../g", "/b/g"},
  17108. {"../..", "/"},
  17109. {"../../", "/"},
  17110. {"../../g", "/g"},
  17111. {"../../../g", "/g"},
  17112. {"g.", "/b/c/g."},
  17113. {".g", "/b/c/.g"},
  17114. {"g..", "/b/c/g.."},
  17115. {"..g", "/b/c/..g"},
  17116. {"./../g", "/b/g"},
  17117. {"./g/.", "/b/c/g/"},
  17118. {"g/./h", "/b/c/g/h"},
  17119. {"g/../h", "/b/c/h"},
  17120. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17121. {"g;x=1/../y", "/b/c/y"},
  17122. {"g?y/./x", "/b/c/g?y/./x"},
  17123. {"g#s/../x", "/b/c/g#s/../x"},
  17124. // Not relative-path references, so left for parse_url.
  17125. {"/g", "/g"},
  17126. {"//g", "//g"},
  17127. {"http://g/x", "http://g/x"},
  17128. {"g:h", "g:h"},
  17129. };
  17130. for (const auto &c : cases) {
  17131. EXPECT_EQ(c.second,
  17132. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17133. << c.first;
  17134. }
  17135. }
  17136. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17137. Server svr;
  17138. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17139. res.set_redirect(req.get_param_value("to"));
  17140. });
  17141. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17142. res.set_content(req.target, "text/plain");
  17143. });
  17144. svr.Get("/other", [](const Request &req, Response &res) {
  17145. res.set_content(req.target, "text/plain");
  17146. });
  17147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17148. auto se = detail::scope_exit([&] {
  17149. svr.stop();
  17150. thread.join();
  17151. ASSERT_FALSE(svr.is_running());
  17152. });
  17153. svr.wait_until_ready();
  17154. const std::vector<std::pair<std::string, std::string>> cases = {
  17155. {"next", "/dir/next"},
  17156. {"./next?x=1", "/dir/next?x=1"},
  17157. {"../other", "/other"},
  17158. };
  17159. for (const auto &c : cases) {
  17160. Client cli(HOST, PORT);
  17161. cli.set_follow_location(true);
  17162. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17163. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17164. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17165. EXPECT_EQ(c.second, res->body) << c.first;
  17166. }
  17167. }
  17168. #ifdef CPPHTTPLIB_SSL_ENABLED
  17169. TEST(RedirectTest, Issue2185_Online) {
  17170. SSLClient client("github.com");
  17171. client.set_follow_location(true);
  17172. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17173. "Coollab-Windows.zip");
  17174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17175. EXPECT_EQ(StatusCode::OK_200, res->status);
  17176. EXPECT_EQ(9920427U, res->body.size());
  17177. }
  17178. #endif
  17179. TEST(VulnerabilityTest, CRLFInjection) {
  17180. Server svr;
  17181. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17182. res.set_content("Hello 1", "text/plain");
  17183. });
  17184. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17185. res.set_content("Hello 2", "text/plain");
  17186. });
  17187. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17188. res.set_content("Hello 3", "text/plain");
  17189. });
  17190. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17191. res.set_content("Hello 4", "text/plain");
  17192. });
  17193. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17194. for (const auto &x : req.headers) {
  17195. auto key = x.first;
  17196. EXPECT_STRNE("evil", key.c_str());
  17197. }
  17198. });
  17199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17200. auto se = detail::scope_exit([&] {
  17201. svr.stop();
  17202. thread.join();
  17203. ASSERT_FALSE(svr.is_running());
  17204. });
  17205. svr.wait_until_ready();
  17206. {
  17207. Client cli(HOST, PORT);
  17208. cli.Post("/test1", "A=B",
  17209. "application/x-www-form-urlencoded\r\nevil: hello1");
  17210. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17211. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17212. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17213. }
  17214. }
  17215. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17216. auto server_thread = std::thread([] {
  17217. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17218. default_socket_options(srv);
  17219. sockaddr_in addr{};
  17220. addr.sin_family = AF_INET;
  17221. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17222. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17223. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17224. ::listen(srv, 1);
  17225. sockaddr_in cli_addr{};
  17226. socklen_t cli_len = sizeof(cli_addr);
  17227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17228. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17229. std::string buf_all;
  17230. char buf[2048];
  17231. ssize_t n;
  17232. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17233. buf_all.append(buf, static_cast<size_t>(n));
  17234. size_t pos;
  17235. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17236. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17237. auto e = request_block.find("\r\n");
  17238. if (e != std::string::npos) {
  17239. auto request_line = request_block.substr(0, e);
  17240. std::string msg =
  17241. "CRLF injection detected in request line: '" + request_line + "'";
  17242. EXPECT_FALSE(true) << msg;
  17243. }
  17244. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17245. ::send(cli,
  17246. #ifdef _WIN32
  17247. static_cast<const char *>(resp.c_str()),
  17248. static_cast<int>(resp.size()),
  17249. #else
  17250. resp.c_str(), resp.size(),
  17251. #endif
  17252. 0);
  17253. buf_all.erase(0, pos + 4);
  17254. }
  17255. }
  17256. detail::close_socket(cli);
  17257. detail::close_socket(srv);
  17258. });
  17259. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17260. auto cli = Client("127.0.0.1", PORT + 1);
  17261. auto headers = Headers{
  17262. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17263. {"Connection", "keep-alive"}};
  17264. auto res = cli.Get("/hi", headers);
  17265. EXPECT_FALSE(res);
  17266. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17267. server_thread.join();
  17268. }
  17269. // A request rejected before any byte reaches the socket must fail right away
  17270. // instead of waiting for a response the server will never send.
  17271. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17272. // The kernel completes the TCP handshake from the listen backlog, so the
  17273. // client connects, but nothing ever reads, responds or closes.
  17274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17275. default_socket_options(srv);
  17276. sockaddr_in addr{};
  17277. addr.sin_family = AF_INET;
  17278. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17279. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17280. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17281. ASSERT_EQ(0, ::listen(srv, 8));
  17282. auto cli = Client("127.0.0.1", PORT + 1);
  17283. cli.set_read_timeout(10, 0);
  17284. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17285. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17286. std::chrono::steady_clock::now() - start)
  17287. .count();
  17288. };
  17289. {
  17290. Request req;
  17291. req.method = "GE T";
  17292. req.path = "/";
  17293. auto start = std::chrono::steady_clock::now();
  17294. auto res = cli.send(req);
  17295. EXPECT_FALSE(res);
  17296. EXPECT_EQ(Error::Write, res.error());
  17297. EXPECT_LT(elapsed_ms(start), 1000);
  17298. }
  17299. {
  17300. auto start = std::chrono::steady_clock::now();
  17301. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17302. EXPECT_FALSE(res);
  17303. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17304. EXPECT_LT(elapsed_ms(start), 1000);
  17305. }
  17306. EXPECT_FALSE(cli.is_socket_open());
  17307. detail::close_socket(srv);
  17308. }
  17309. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17310. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17311. default_socket_options(srv);
  17312. sockaddr_in addr{};
  17313. addr.sin_family = AF_INET;
  17314. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17315. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17316. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17317. ASSERT_EQ(0, ::listen(srv, 1));
  17318. std::string received;
  17319. auto server_thread = std::thread([&] {
  17320. auto sock = ::accept(srv, nullptr, nullptr);
  17321. if (sock == INVALID_SOCKET) { return; }
  17322. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17323. char buf[2048];
  17324. ssize_t n;
  17325. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17326. received.append(buf, static_cast<size_t>(n));
  17327. }
  17328. detail::close_socket(sock);
  17329. });
  17330. {
  17331. auto cli = Client("127.0.0.1", PORT + 1);
  17332. // "Z" sorts after the default headers, so writing straight to the socket
  17333. // would have sent the request line and those headers before the rejection.
  17334. auto handle =
  17335. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17336. EXPECT_FALSE(handle.is_valid());
  17337. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17338. }
  17339. server_thread.join();
  17340. detail::close_socket(srv);
  17341. EXPECT_TRUE(received.empty()) << received;
  17342. }
  17343. TEST(PathParamsTest, StaticMatch) {
  17344. const auto pattern = "/users/all";
  17345. detail::PathParamsMatcher matcher(pattern);
  17346. Request request;
  17347. request.path = "/users/all";
  17348. ASSERT_TRUE(matcher.match(request));
  17349. std::unordered_map<std::string, std::string> expected_params = {};
  17350. EXPECT_EQ(request.path_params, expected_params);
  17351. }
  17352. TEST(PathParamsTest, StaticMismatch) {
  17353. const auto pattern = "/users/all";
  17354. detail::PathParamsMatcher matcher(pattern);
  17355. Request request;
  17356. request.path = "/users/1";
  17357. ASSERT_FALSE(matcher.match(request));
  17358. }
  17359. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17360. const auto pattern = "/users/:id/subscriptions";
  17361. detail::PathParamsMatcher matcher(pattern);
  17362. Request request;
  17363. request.path = "/users/42/subscriptions";
  17364. ASSERT_TRUE(matcher.match(request));
  17365. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17366. EXPECT_EQ(request.path_params, expected_params);
  17367. }
  17368. TEST(PathParamsTest, SingleParamInTheEnd) {
  17369. const auto pattern = "/users/:id";
  17370. detail::PathParamsMatcher matcher(pattern);
  17371. Request request;
  17372. request.path = "/users/24";
  17373. ASSERT_TRUE(matcher.match(request));
  17374. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17375. EXPECT_EQ(request.path_params, expected_params);
  17376. }
  17377. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17378. const auto pattern = "/users/:id/";
  17379. detail::PathParamsMatcher matcher(pattern);
  17380. Request request;
  17381. request.path = "/users/42/";
  17382. ASSERT_TRUE(matcher.match(request));
  17383. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17384. EXPECT_EQ(request.path_params, expected_params);
  17385. }
  17386. TEST(PathParamsTest, EmptyParam) {
  17387. const auto pattern = "/users/:id/";
  17388. detail::PathParamsMatcher matcher(pattern);
  17389. Request request;
  17390. request.path = "/users//";
  17391. ASSERT_TRUE(matcher.match(request));
  17392. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17393. EXPECT_EQ(request.path_params, expected_params);
  17394. }
  17395. TEST(PathParamsTest, FragmentMismatch) {
  17396. const auto pattern = "/users/:id/";
  17397. detail::PathParamsMatcher matcher(pattern);
  17398. Request request;
  17399. request.path = "/admins/24/";
  17400. ASSERT_FALSE(matcher.match(request));
  17401. }
  17402. TEST(PathParamsTest, ExtraFragments) {
  17403. const auto pattern = "/users/:id";
  17404. detail::PathParamsMatcher matcher(pattern);
  17405. Request request;
  17406. request.path = "/users/42/subscriptions";
  17407. ASSERT_FALSE(matcher.match(request));
  17408. }
  17409. TEST(PathParamsTest, MissingTrailingParam) {
  17410. const auto pattern = "/users/:id";
  17411. detail::PathParamsMatcher matcher(pattern);
  17412. Request request;
  17413. request.path = "/users";
  17414. ASSERT_FALSE(matcher.match(request));
  17415. }
  17416. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17417. const auto pattern = "/users/:id/subscriptions";
  17418. detail::PathParamsMatcher matcher(pattern);
  17419. Request request;
  17420. request.path = "/users/subscriptions";
  17421. ASSERT_FALSE(matcher.match(request));
  17422. }
  17423. TEST(PathParamsTest, MultipleParams) {
  17424. const auto pattern = "/users/:userid/subscriptions/:subid";
  17425. detail::PathParamsMatcher matcher(pattern);
  17426. Request request;
  17427. request.path = "/users/42/subscriptions/2";
  17428. ASSERT_TRUE(matcher.match(request));
  17429. std::unordered_map<std::string, std::string> expected_params = {
  17430. {"userid", "42"}, {"subid", "2"}};
  17431. EXPECT_EQ(request.path_params, expected_params);
  17432. }
  17433. TEST(PathParamsTest, SequenceOfParams) {
  17434. const auto pattern = "/values/:x/:y/:z";
  17435. detail::PathParamsMatcher matcher(pattern);
  17436. Request request;
  17437. request.path = "/values/1/2/3";
  17438. ASSERT_TRUE(matcher.match(request));
  17439. std::unordered_map<std::string, std::string> expected_params = {
  17440. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17441. EXPECT_EQ(request.path_params, expected_params);
  17442. }
  17443. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17444. const auto pattern = "/prefix:suffix";
  17445. detail::PathParamsMatcher matcher(pattern);
  17446. Request request;
  17447. request.path = "/prefix:suffix";
  17448. ASSERT_TRUE(matcher.match(request));
  17449. const std::unordered_map<std::string, std::string> expected_params = {};
  17450. EXPECT_EQ(request.path_params, expected_params);
  17451. }
  17452. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17453. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17454. // calling thread's stack on a long enough path for a quantified pattern;
  17455. // RegexMatcher must refuse to run regex matching on paths beyond
  17456. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17457. detail::RegexMatcher matcher("/files/(.*)");
  17458. Request within_limit;
  17459. within_limit.path = "/files/" + std::string(10, 'A');
  17460. EXPECT_TRUE(matcher.match(within_limit));
  17461. Request over_limit;
  17462. over_limit.path =
  17463. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17464. EXPECT_FALSE(matcher.match(over_limit));
  17465. }
  17466. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17467. Server svr;
  17468. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. auto port = svr.bind_to_any_port(HOST);
  17472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17473. auto se = detail::scope_exit([&] {
  17474. svr.stop();
  17475. thread.join();
  17476. ASSERT_FALSE(svr.is_running());
  17477. });
  17478. svr.wait_until_ready();
  17479. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17480. // request URI limit; this used to be able to crash the process.
  17481. std::string path =
  17482. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17483. std::string req = "GET " + path +
  17484. " HTTP/1.1\r\n"
  17485. "Host: " +
  17486. std::string(HOST) + ":" + std::to_string(port) +
  17487. "\r\n"
  17488. "Connection: close\r\n"
  17489. "\r\n";
  17490. std::string response;
  17491. ASSERT_TRUE(send_request(5, req, &response, port));
  17492. EXPECT_NE(std::string::npos, response.find("404"));
  17493. }
  17494. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17495. Server svr;
  17496. auto handler = [](const Request & /*req*/, Response &res) {
  17497. res.set_content("hit", "text/plain");
  17498. };
  17499. // No regex metacharacter, so this one is compared literally
  17500. svr.Get("/literal/route", handler);
  17501. // '.' is a regex metacharacter, so this one must keep regex semantics
  17502. svr.Get("/a.c", handler);
  17503. auto port = svr.bind_to_any_port(HOST);
  17504. std::thread t([&]() { svr.listen_after_bind(); });
  17505. auto se = detail::scope_exit([&] {
  17506. svr.stop();
  17507. t.join();
  17508. ASSERT_FALSE(svr.is_running());
  17509. });
  17510. svr.wait_until_ready();
  17511. Client cli(HOST, port);
  17512. struct {
  17513. const char *path;
  17514. int status;
  17515. } cases[] = {
  17516. {"/literal/route", StatusCode::OK_200},
  17517. {"/literal/routes", StatusCode::NotFound_404},
  17518. {"/literal/rout", StatusCode::NotFound_404},
  17519. {"/abc", StatusCode::OK_200},
  17520. {"/a.c", StatusCode::OK_200},
  17521. };
  17522. for (const auto &x : cases) {
  17523. auto res = cli.Get(x.path);
  17524. ASSERT_TRUE(res) << x.path;
  17525. EXPECT_EQ(x.status, res->status) << x.path;
  17526. }
  17527. }
  17528. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17529. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17530. // from exhausting the stack, so it must only constrain routes that actually
  17531. // run a regular expression. A literal route is matched by comparison and
  17532. // stays usable at any length.
  17533. Server svr;
  17534. const std::string pattern =
  17535. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17536. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17537. res.set_content("hit", "text/plain");
  17538. });
  17539. auto port = svr.bind_to_any_port(HOST);
  17540. std::thread t([&]() { svr.listen_after_bind(); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. Client cli(HOST, port);
  17548. auto res = cli.Get(pattern);
  17549. ASSERT_TRUE(res);
  17550. EXPECT_EQ(StatusCode::OK_200, res->status);
  17551. }
  17552. TEST(ParseUrlTest, VariousPatterns) {
  17553. {
  17554. detail::UrlComponents uc;
  17555. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17556. EXPECT_EQ("http", uc.scheme);
  17557. EXPECT_EQ("example.com", uc.host);
  17558. EXPECT_EQ("8080", uc.port);
  17559. EXPECT_EQ("/path", uc.path);
  17560. EXPECT_EQ("?q=1", uc.query);
  17561. }
  17562. {
  17563. detail::UrlComponents uc;
  17564. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17565. EXPECT_EQ("https", uc.scheme);
  17566. EXPECT_EQ("example.com", uc.host);
  17567. EXPECT_TRUE(uc.port.empty());
  17568. EXPECT_EQ("/path", uc.path);
  17569. }
  17570. {
  17571. detail::UrlComponents uc;
  17572. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17573. EXPECT_EQ("::1", uc.host);
  17574. EXPECT_EQ("8080", uc.port);
  17575. EXPECT_EQ("/path", uc.path);
  17576. }
  17577. {
  17578. detail::UrlComponents uc;
  17579. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17580. }
  17581. {
  17582. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17583. // the path while the connection still targets the bracketed host.
  17584. detail::UrlComponents uc;
  17585. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17586. }
  17587. {
  17588. detail::UrlComponents uc;
  17589. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17590. }
  17591. {
  17592. detail::UrlComponents uc;
  17593. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17594. EXPECT_EQ("::1", uc.host);
  17595. EXPECT_TRUE(uc.port.empty());
  17596. EXPECT_EQ("/path", uc.path);
  17597. }
  17598. {
  17599. detail::UrlComponents uc;
  17600. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17601. EXPECT_TRUE(uc.scheme.empty());
  17602. EXPECT_EQ("example.com", uc.host);
  17603. EXPECT_EQ("/path", uc.path);
  17604. EXPECT_EQ("?q=1", uc.query);
  17605. }
  17606. {
  17607. detail::UrlComponents uc;
  17608. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17609. EXPECT_TRUE(uc.host.empty());
  17610. EXPECT_EQ("/path", uc.path);
  17611. EXPECT_EQ("?q=1", uc.query);
  17612. }
  17613. {
  17614. detail::UrlComponents uc;
  17615. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17616. EXPECT_EQ("example.com", uc.host);
  17617. EXPECT_EQ("8080", uc.port);
  17618. }
  17619. {
  17620. // Unix socket path — must not be parsed as host
  17621. detail::UrlComponents uc;
  17622. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17623. EXPECT_TRUE(uc.host.empty());
  17624. }
  17625. {
  17626. detail::UrlComponents uc;
  17627. ASSERT_TRUE(detail::parse_url("", uc));
  17628. EXPECT_TRUE(uc.host.empty());
  17629. EXPECT_TRUE(uc.path.empty());
  17630. }
  17631. {
  17632. detail::UrlComponents uc;
  17633. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17634. }
  17635. {
  17636. detail::UrlComponents uc;
  17637. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17638. }
  17639. {
  17640. // Accepted by parse_url; callers restrict to http/https
  17641. detail::UrlComponents uc;
  17642. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17643. EXPECT_EQ("ftp", uc.scheme);
  17644. }
  17645. {
  17646. detail::UrlComponents uc;
  17647. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17648. }
  17649. {
  17650. detail::UrlComponents uc;
  17651. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17652. }
  17653. }
  17654. TEST(ParseUrlTest, FragmentHandling) {
  17655. {
  17656. detail::UrlComponents uc;
  17657. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17658. EXPECT_EQ("/path", uc.path);
  17659. EXPECT_TRUE(uc.query.empty());
  17660. }
  17661. {
  17662. detail::UrlComponents uc;
  17663. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17664. EXPECT_TRUE(uc.path.empty());
  17665. EXPECT_TRUE(uc.query.empty());
  17666. }
  17667. }
  17668. TEST(ParseUrlTest, UserinfoHandling) {
  17669. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17670. // parsers would see evil.com as the host.
  17671. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17672. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17673. for (auto url : urls) {
  17674. detail::UrlComponents uc;
  17675. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17676. }
  17677. }
  17678. TEST(ParseUrlTest, IPv6EdgeCases) {
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17682. EXPECT_TRUE(uc.scheme.empty());
  17683. EXPECT_EQ("::1", uc.host);
  17684. EXPECT_EQ("8080", uc.port);
  17685. }
  17686. {
  17687. // Zone ID '%25' is not in [a-fA-F0-9:]
  17688. detail::UrlComponents uc;
  17689. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17690. }
  17691. }
  17692. TEST(ParseUrlTest, SchemeEdgeCases) {
  17693. {
  17694. detail::UrlComponents uc;
  17695. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17696. }
  17697. {
  17698. detail::UrlComponents uc;
  17699. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17700. }
  17701. {
  17702. detail::UrlComponents uc;
  17703. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17704. }
  17705. }
  17706. TEST(ParseUrlTest, PortEdgeCases) {
  17707. {
  17708. detail::UrlComponents uc;
  17709. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17710. EXPECT_TRUE(uc.port.empty());
  17711. EXPECT_EQ("/path", uc.path);
  17712. }
  17713. {
  17714. // parse_url accepts any port string; validation is done by parse_port
  17715. detail::UrlComponents uc;
  17716. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17717. EXPECT_EQ("abc", uc.port);
  17718. }
  17719. }
  17720. TEST(ParseUrlTest, WebSocketPatterns) {
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17724. EXPECT_EQ("ws", uc.scheme);
  17725. EXPECT_EQ("echo.example.com", uc.host);
  17726. EXPECT_EQ("8080", uc.port);
  17727. EXPECT_EQ("/ws", uc.path);
  17728. }
  17729. {
  17730. detail::UrlComponents uc;
  17731. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17732. EXPECT_EQ("wss", uc.scheme);
  17733. EXPECT_EQ("echo.example.com", uc.host);
  17734. EXPECT_TRUE(uc.port.empty());
  17735. EXPECT_EQ("/ws", uc.path);
  17736. }
  17737. }
  17738. TEST(ParseUrlTest, QueryOnly) {
  17739. detail::UrlComponents uc;
  17740. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17741. EXPECT_TRUE(uc.host.empty());
  17742. EXPECT_TRUE(uc.path.empty());
  17743. EXPECT_EQ("?q=1&r=2", uc.query);
  17744. }
  17745. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17746. detail::UrlComponents uc;
  17747. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17748. EXPECT_TRUE(uc.scheme.empty());
  17749. EXPECT_EQ("example.com", uc.host);
  17750. EXPECT_EQ("443", uc.port);
  17751. EXPECT_EQ("/path", uc.path);
  17752. }
  17753. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17754. // If ipv6 regex working, regex match codepath is taken.
  17755. // else port will default to 80 in Client impl
  17756. int clientImplMagicPort = 80;
  17757. int port = 4321;
  17758. // above ports must be different to avoid false negative
  17759. EXPECT_NE(clientImplMagicPort, port);
  17760. std::string ipV6TestURL = "http://[ff06::c3]";
  17761. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17762. CLIENT_PRIVATE_KEY_FILE);
  17763. EXPECT_EQ(cli.port(), port);
  17764. }
  17765. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17766. auto file_path = "./www/dir/index.html";
  17767. auto dir_path = "./www/dir";
  17768. detail::FileStat stat_file(file_path);
  17769. EXPECT_TRUE(stat_file.is_file());
  17770. EXPECT_FALSE(stat_file.is_dir());
  17771. detail::FileStat stat_dir(dir_path);
  17772. EXPECT_FALSE(stat_dir.is_file());
  17773. EXPECT_TRUE(stat_dir.is_dir());
  17774. }
  17775. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17776. // IPv4 with default HTTP port (80)
  17777. EXPECT_EQ("example.com",
  17778. detail::make_host_and_port_string("example.com", 80, false));
  17779. // IPv4 with default HTTPS port (443)
  17780. EXPECT_EQ("example.com",
  17781. detail::make_host_and_port_string("example.com", 443, true));
  17782. // IPv4 with non-default HTTP port
  17783. EXPECT_EQ("example.com:8080",
  17784. detail::make_host_and_port_string("example.com", 8080, false));
  17785. // IPv4 with non-default HTTPS port
  17786. EXPECT_EQ("example.com:8443",
  17787. detail::make_host_and_port_string("example.com", 8443, true));
  17788. // IPv6 with default HTTP port (80)
  17789. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17790. // IPv6 with default HTTPS port (443)
  17791. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17792. // IPv6 with non-default HTTP port
  17793. EXPECT_EQ("[::1]:8080",
  17794. detail::make_host_and_port_string("::1", 8080, false));
  17795. // IPv6 with non-default HTTPS port
  17796. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17797. // IPv6 full address with default port
  17798. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17799. detail::make_host_and_port_string(
  17800. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17801. // IPv6 full address with non-default port
  17802. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17803. detail::make_host_and_port_string(
  17804. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17805. // IPv6 localhost with non-default port
  17806. EXPECT_EQ("[::1]:3000",
  17807. detail::make_host_and_port_string("::1", 3000, false));
  17808. // IPv6 with zone ID (link-local address) with default port
  17809. EXPECT_EQ("[fe80::1%eth0]",
  17810. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17811. // IPv6 with zone ID (link-local address) with non-default port
  17812. EXPECT_EQ("[fe80::1%eth0]:8080",
  17813. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17814. // Edge case: Port 443 with is_ssl=false (should add port)
  17815. EXPECT_EQ("example.com:443",
  17816. detail::make_host_and_port_string("example.com", 443, false));
  17817. // Edge case: Port 80 with is_ssl=true (should add port)
  17818. EXPECT_EQ("example.com:80",
  17819. detail::make_host_and_port_string("example.com", 80, true));
  17820. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17821. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17822. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17823. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17824. // Security fix: Already bracketed IPv6 should not get double brackets
  17825. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17826. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17827. EXPECT_EQ("[::1]:8080",
  17828. detail::make_host_and_port_string("[::1]", 8080, false));
  17829. EXPECT_EQ("[2001:db8::1]:8080",
  17830. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17831. EXPECT_EQ("[fe80::1%eth0]",
  17832. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17833. EXPECT_EQ("[fe80::1%eth0]:8080",
  17834. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17835. // Edge case: Empty host (should return as-is)
  17836. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17837. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17838. // This is a known limitation but shouldn't crash
  17839. EXPECT_EQ("[host:name]",
  17840. detail::make_host_and_port_string("host:name", 80, false));
  17841. // Port number edge cases (no validation, but should not crash)
  17842. EXPECT_EQ("example.com:0",
  17843. detail::make_host_and_port_string("example.com", 0, false));
  17844. EXPECT_EQ("example.com:-1",
  17845. detail::make_host_and_port_string("example.com", -1, false));
  17846. EXPECT_EQ("example.com:65535",
  17847. detail::make_host_and_port_string("example.com", 65535, false));
  17848. EXPECT_EQ("example.com:65536",
  17849. detail::make_host_and_port_string("example.com", 65536, false));
  17850. }
  17851. #ifdef CPPHTTPLIB_SSL_ENABLED
  17852. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17853. httplib::SSLClient cli("roblox.com", 443);
  17854. cli.set_follow_location(true);
  17855. auto res = cli.Get("/");
  17856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17857. EXPECT_EQ(StatusCode::OK_200, res->status);
  17858. }
  17859. #endif
  17860. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17861. Server svr;
  17862. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17863. EXPECT_EQ(res.status, 400);
  17864. });
  17865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17866. auto se = detail::scope_exit([&] {
  17867. svr.stop();
  17868. thread.join();
  17869. ASSERT_FALSE(svr.is_running());
  17870. });
  17871. svr.wait_until_ready();
  17872. Client cli(HOST, PORT);
  17873. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17874. }
  17875. TEST(InvalidHeaderCharsTest, is_field_name) {
  17876. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17877. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17878. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17879. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17880. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17881. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17882. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17883. EXPECT_FALSE(detail::fields::is_field_name(""));
  17884. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17885. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17886. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17887. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17888. }
  17889. TEST(InvalidHeaderCharsTest, is_field_value) {
  17890. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17891. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17892. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17893. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17894. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17895. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17896. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17897. EXPECT_TRUE(detail::fields::is_field_value(""));
  17898. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17899. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17900. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17901. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17902. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17903. }
  17904. TEST(InvalidHeaderCharsTest, OnServer) {
  17905. Server svr;
  17906. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17907. std::string header = "Not Set";
  17908. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17909. res.set_header(header, "value");
  17910. res.set_content("Page Content Page Content", "text/plain");
  17911. });
  17912. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17913. std::string header = "Not Set";
  17914. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17915. res.set_header("X-Test", header);
  17916. res.set_content("Page Content Page Content", "text/plain");
  17917. });
  17918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17919. auto se = detail::scope_exit([&] {
  17920. svr.stop();
  17921. thread.join();
  17922. ASSERT_FALSE(svr.is_running());
  17923. });
  17924. svr.wait_until_ready();
  17925. Client cli(HOST, PORT);
  17926. {
  17927. auto res = cli.Get(
  17928. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17930. EXPECT_EQ("Page Content Page Content", res->body);
  17931. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17932. }
  17933. {
  17934. auto res = cli.Get(
  17935. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17937. EXPECT_EQ("Page Content Page Content", res->body);
  17938. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17939. }
  17940. }
  17941. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17942. auto handled = false;
  17943. Server svr;
  17944. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17945. thread t = thread([&] { svr.listen(HOST, PORT); });
  17946. auto se = detail::scope_exit([&] {
  17947. svr.stop();
  17948. t.join();
  17949. ASSERT_FALSE(svr.is_running());
  17950. ASSERT_FALSE(handled);
  17951. });
  17952. svr.wait_until_ready();
  17953. auto req = "POST /test HTTP/1.1\r\n"
  17954. "Content-Length: x\r\n"
  17955. "\r\n";
  17956. std::string response;
  17957. ASSERT_TRUE(send_request(1, req, &response));
  17958. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17959. response.substr(0, response.find("\r\n")));
  17960. }
  17961. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17962. // case-insensitive, and a server that receives a 100-continue expectation in
  17963. // an HTTP/1.0 request MUST ignore it.
  17964. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17965. std::string response;
  17966. ASSERT_TRUE(send_request(1, req, &response, port));
  17967. *got_100 = response.find("100 Continue") != std::string::npos;
  17968. }
  17969. class ExpectTokenTest : public ::testing::Test {
  17970. protected:
  17971. void SetUp() override {
  17972. svr_.Post("/p", [](const Request &, Response &res) {
  17973. res.set_content("ok", "text/plain");
  17974. });
  17975. port_ = svr_.bind_to_any_port(HOST);
  17976. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17977. svr_.wait_until_ready();
  17978. }
  17979. void TearDown() override {
  17980. svr_.stop();
  17981. if (thread_.joinable()) { thread_.join(); }
  17982. }
  17983. std::string request(const char *version, const char *expect_value) const {
  17984. return std::string("POST /p ") + version +
  17985. "\r\n"
  17986. "Host: localhost\r\n"
  17987. "Content-Length: 2\r\n"
  17988. "Connection: close\r\n"
  17989. "Expect: " +
  17990. expect_value +
  17991. "\r\n"
  17992. "\r\n"
  17993. "hi";
  17994. }
  17995. Server svr_;
  17996. int port_ = 0;
  17997. thread thread_;
  17998. };
  17999. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18000. bool got_100 = false;
  18001. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18002. EXPECT_TRUE(got_100);
  18003. }
  18004. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18005. bool got_100 = true;
  18006. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18007. EXPECT_FALSE(got_100);
  18008. }
  18009. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18010. bool got_100 = false;
  18011. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18012. EXPECT_TRUE(got_100);
  18013. }
  18014. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18015. bool got_100 = false;
  18016. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18017. EXPECT_TRUE(got_100);
  18018. }
  18019. // `100 Continue` is sent only when the server starts reading the body, so a
  18020. // request rejected before that never invites the client to send it. The
  18021. // requests below carry the expectation but withhold the body, as a client
  18022. // waiting for `100 Continue` would.
  18023. // A POST that expects `100 Continue` and withholds its two-byte body.
  18024. static std::string expect_headers_only(const std::string &path) {
  18025. return "POST " + path +
  18026. " HTTP/1.1\r\n"
  18027. "Host: localhost\r\n"
  18028. "Content-Length: 2\r\n"
  18029. "Expect: 100-continue\r\n"
  18030. "\r\n";
  18031. }
  18032. class ExpectLazyContinueTest : public ::testing::Test {
  18033. protected:
  18034. void SetUp() override {
  18035. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18036. if (req.path == "/pre-routing") {
  18037. res.status = StatusCode::Unauthorized_401;
  18038. return Server::HandlerResponse::Handled;
  18039. }
  18040. return Server::HandlerResponse::Unhandled;
  18041. });
  18042. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18043. if (req.matched_route == "/pre-request") {
  18044. res.status = StatusCode::Forbidden_403;
  18045. return Server::HandlerResponse::Handled;
  18046. }
  18047. return Server::HandlerResponse::Unhandled;
  18048. });
  18049. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18050. res.set_content("ok", "text/plain");
  18051. });
  18052. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18053. res.set_content("ok", "text/plain");
  18054. });
  18055. svr_.Post("/reader-used", [](const Request &, Response &res,
  18056. const ContentReader &content_reader) {
  18057. std::string body;
  18058. content_reader([&](const char *data, size_t len) {
  18059. body.append(data, len);
  18060. return true;
  18061. });
  18062. res.set_content(body, "text/plain");
  18063. });
  18064. svr_.Post("/reader-unused",
  18065. [](const Request &, Response &res, const ContentReader &) {
  18066. res.set_content("ignored", "text/plain");
  18067. });
  18068. port_ = svr_.bind_to_any_port(HOST);
  18069. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18070. svr_.wait_until_ready();
  18071. }
  18072. void TearDown() override {
  18073. svr_.stop();
  18074. if (thread_.joinable()) { thread_.join(); }
  18075. }
  18076. // Sends `req` and reads until the server closes the connection. Returns
  18077. // false if the read had to wait for the client-side timeout instead.
  18078. bool send_until_closed(const std::string &req, std::string *resp) const {
  18079. auto start = std::chrono::steady_clock::now();
  18080. if (!send_request(3, req, resp, port_)) { return false; }
  18081. auto elapsed = std::chrono::steady_clock::now() - start;
  18082. return elapsed < std::chrono::seconds(2);
  18083. }
  18084. // The final response comes without `100 Continue`, and the server closes
  18085. // the connection since the body may or may not follow.
  18086. void expect_final_without_interim(const std::string &path,
  18087. const char *status_line) const {
  18088. std::string resp;
  18089. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18090. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18091. EXPECT_EQ(0u, resp.find(status_line));
  18092. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18093. }
  18094. Server svr_;
  18095. int port_ = 0;
  18096. thread thread_;
  18097. };
  18098. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18099. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18100. }
  18101. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18102. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18103. }
  18104. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18105. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18106. }
  18107. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18108. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18109. }
  18110. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18111. // The body follows once `100 Continue` has had time to arrive.
  18112. auto req = expect_headers_only("/reader-used");
  18113. req.insert(req.size() - 2, "Connection: close\r\n");
  18114. std::string resp;
  18115. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18116. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18117. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18118. EXPECT_NE(std::string::npos, resp.find("hi"));
  18119. }
  18120. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18121. // Large enough for the client to add `Expect: 100-continue` itself.
  18122. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18123. std::atomic<bool> body_sent{false};
  18124. Client cli(HOST, port_);
  18125. auto res = cli.Post(
  18126. "/pre-request", length,
  18127. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18128. body_sent = true;
  18129. std::string chunk(len, 'x');
  18130. sink.write(chunk.data(), chunk.size());
  18131. return true;
  18132. },
  18133. "application/octet-stream");
  18134. ASSERT_TRUE(res);
  18135. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18136. EXPECT_FALSE(body_sent);
  18137. }
  18138. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18139. Server svr;
  18140. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18141. return StatusCode::ExpectationFailed_417;
  18142. });
  18143. svr.Post("/p", [](const Request &, Response &res) {
  18144. res.set_content("ok", "text/plain");
  18145. });
  18146. auto port = svr.bind_to_any_port(HOST);
  18147. thread t = thread([&] { svr.listen_after_bind(); });
  18148. auto se = detail::scope_exit([&] {
  18149. svr.stop();
  18150. t.join();
  18151. });
  18152. svr.wait_until_ready();
  18153. std::string resp;
  18154. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18155. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18156. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18157. // Exactly one response: the route handler must not run after the 417.
  18158. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18159. }
  18160. #ifndef _WIN32
  18161. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18162. static constexpr char reject[] = "Unauthorized";
  18163. static constexpr char accept[] = "Upload accepted";
  18164. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18165. Server svr;
  18166. svr.set_expect_100_continue_handler(
  18167. [](const Request & /*req*/, Response &res) {
  18168. res.status = StatusCode::Unauthorized_401;
  18169. res.set_content(reject, "text/plain");
  18170. return res.status;
  18171. });
  18172. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18173. res.set_content(accept, "text/plain");
  18174. });
  18175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18176. auto se = detail::scope_exit([&] {
  18177. svr.stop();
  18178. thread.join();
  18179. ASSERT_FALSE(svr.is_running());
  18180. });
  18181. svr.wait_until_ready();
  18182. {
  18183. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18184. curl_easy_init(), &curl_easy_cleanup};
  18185. ASSERT_NE(curl, nullptr);
  18186. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18187. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18188. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18189. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18190. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18191. &curl_slist_free_all};
  18192. ASSERT_NE(list, nullptr);
  18193. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18194. struct read_data {
  18195. uint64_t read_size;
  18196. uint64_t total_size;
  18197. } data = {0, total_size};
  18198. using read_callback_t =
  18199. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18200. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18201. void *userdata) -> size_t {
  18202. read_data *d = (read_data *)userdata;
  18203. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18204. std::fill_n(ptr, size * nmemb, 'A');
  18205. d->read_size += size * nmemb;
  18206. return size * nmemb;
  18207. };
  18208. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18209. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18210. std::vector<char> buffer;
  18211. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18212. using write_callback_t =
  18213. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18214. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18215. void *userdata) -> size_t {
  18216. std::vector<char> *buf = (std::vector<char> *)userdata;
  18217. buf->reserve(buf->size() + size * nmemb + 1);
  18218. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18219. return size * nmemb;
  18220. };
  18221. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18222. {
  18223. const auto res = curl_easy_perform(curl.get());
  18224. ASSERT_EQ(res, CURLE_OK);
  18225. }
  18226. {
  18227. auto response_code = long{};
  18228. const auto res =
  18229. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18230. ASSERT_EQ(res, CURLE_OK);
  18231. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18232. }
  18233. {
  18234. auto dl = curl_off_t{};
  18235. const auto res =
  18236. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18237. ASSERT_EQ(res, CURLE_OK);
  18238. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18239. }
  18240. {
  18241. buffer.push_back('\0');
  18242. ASSERT_STRCASEEQ(buffer.data(), reject);
  18243. }
  18244. }
  18245. }
  18246. #endif
  18247. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18248. // Regression test for #2458.
  18249. //
  18250. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18251. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18252. // ticket can make the client socket spuriously readable during the
  18253. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18254. // the client withholds the body and then blocks reading a response that never
  18255. // comes, failing with `Failed to read connection`.
  18256. //
  18257. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18258. // within the timeout. This raw OpenSSL server deliberately never sends
  18259. // `100 Continue`; the client must still deliver the body and receive 200.
  18260. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18261. signal(SIGPIPE, SIG_IGN);
  18262. const auto port = PORT + 4;
  18263. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18264. ASSERT_NE(srv, INVALID_SOCKET);
  18265. int opt = 1;
  18266. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18267. sockaddr_in addr{};
  18268. addr.sin_family = AF_INET;
  18269. addr.sin_port = htons(static_cast<uint16_t>(port));
  18270. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18271. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18272. ASSERT_EQ(0, ::listen(srv, 1));
  18273. std::atomic<size_t> server_body_bytes{0};
  18274. auto server_thread = std::thread([&] {
  18275. sockaddr_in cli_addr{};
  18276. socklen_t cli_len = sizeof(cli_addr);
  18277. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18278. if (cli == INVALID_SOCKET) { return; }
  18279. // Bound the lifetime of the server side so a buggy client (which never
  18280. // sends the body) cannot make this thread block forever on join.
  18281. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18282. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18283. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18284. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18285. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18286. SSL *ssl = SSL_new(ctx);
  18287. SSL_set_fd(ssl, static_cast<int>(cli));
  18288. if (SSL_accept(ssl) > 0) {
  18289. // Read the request headers. Reading here also flushes the TLS 1.3
  18290. // session tickets to the client. Deliberately do NOT send
  18291. // `100 Continue`.
  18292. std::string buf;
  18293. char tmp[1024];
  18294. while (buf.find("\r\n\r\n") == std::string::npos) {
  18295. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18296. if (n <= 0) { break; }
  18297. buf.append(tmp, static_cast<size_t>(n));
  18298. }
  18299. // A correct client sends the body now; count what arrives.
  18300. auto pos = buf.find("\r\n\r\n");
  18301. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18302. while (body < 4096) {
  18303. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18304. if (n <= 0) { break; }
  18305. body += static_cast<size_t>(n);
  18306. }
  18307. server_body_bytes = body;
  18308. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18309. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18310. SSL_shutdown(ssl);
  18311. }
  18312. SSL_free(ssl);
  18313. detail::close_socket(cli);
  18314. SSL_CTX_free(ctx);
  18315. });
  18316. auto se = detail::scope_exit([&] {
  18317. server_thread.join();
  18318. detail::close_socket(srv);
  18319. });
  18320. SSLClient cli("127.0.0.1", port);
  18321. cli.enable_server_certificate_verification(false);
  18322. cli.set_connection_timeout(5, 0);
  18323. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18324. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18325. std::string body(4096, 'A');
  18326. auto res = cli.Put("/api/test", body, "application/json");
  18327. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18328. EXPECT_EQ(StatusCode::OK_200, res->status);
  18329. EXPECT_EQ(body.size(), server_body_bytes.load());
  18330. }
  18331. #endif
  18332. template <typename S, typename C>
  18333. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18334. svr.Get("/stream", [&](const Request &, Response &res) {
  18335. auto data = new std::string("01234567890123456789");
  18336. res.set_content_provider(
  18337. data->size(), "text/plain",
  18338. [&, data](size_t offset, size_t length, DataSink &sink) {
  18339. const size_t DATA_CHUNK_SIZE = 4;
  18340. const auto &d = *data;
  18341. std::this_thread::sleep_for(std::chrono::seconds(1));
  18342. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18343. return true;
  18344. },
  18345. [data](bool success) {
  18346. EXPECT_FALSE(success);
  18347. delete data;
  18348. });
  18349. });
  18350. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18351. auto i = new size_t(0);
  18352. res.set_content_provider(
  18353. "text/plain",
  18354. [i](size_t, DataSink &sink) {
  18355. if (*i < 5) {
  18356. std::this_thread::sleep_for(std::chrono::seconds(1));
  18357. sink.write("abcd", 4);
  18358. (*i)++;
  18359. } else {
  18360. sink.done();
  18361. }
  18362. return true;
  18363. },
  18364. [i](bool success) {
  18365. EXPECT_FALSE(success);
  18366. delete i;
  18367. });
  18368. });
  18369. svr.Get("/chunked", [&](const Request &, Response &res) {
  18370. auto i = new size_t(0);
  18371. res.set_chunked_content_provider(
  18372. "text/plain",
  18373. [i](size_t, DataSink &sink) {
  18374. if (*i < 5) {
  18375. std::this_thread::sleep_for(std::chrono::seconds(1));
  18376. sink.os << "abcd";
  18377. (*i)++;
  18378. } else {
  18379. sink.done();
  18380. }
  18381. return true;
  18382. },
  18383. [i](bool success) {
  18384. EXPECT_FALSE(success);
  18385. delete i;
  18386. });
  18387. });
  18388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18389. auto se = detail::scope_exit([&] {
  18390. svr.stop();
  18391. listen_thread.join();
  18392. ASSERT_FALSE(svr.is_running());
  18393. });
  18394. svr.wait_until_ready();
  18395. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18396. {
  18397. auto start = std::chrono::steady_clock::now();
  18398. auto res = cli.Get("/stream");
  18399. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18400. std::chrono::steady_clock::now() - start)
  18401. .count();
  18402. ASSERT_FALSE(res);
  18403. EXPECT_EQ(Error::Read, res.error());
  18404. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18405. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18406. }
  18407. {
  18408. auto start = std::chrono::steady_clock::now();
  18409. auto res = cli.Get("/stream_without_length");
  18410. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18411. std::chrono::steady_clock::now() - start)
  18412. .count();
  18413. ASSERT_FALSE(res);
  18414. EXPECT_EQ(Error::Read, res.error());
  18415. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18416. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18417. }
  18418. {
  18419. auto start = std::chrono::steady_clock::now();
  18420. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18421. EXPECT_EQ("abcd", string(data, data_length));
  18422. return true;
  18423. });
  18424. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18425. std::chrono::steady_clock::now() - start)
  18426. .count();
  18427. ASSERT_FALSE(res);
  18428. EXPECT_EQ(Error::Read, res.error());
  18429. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18430. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18431. }
  18432. }
  18433. TEST(MaxTimeoutTest, ContentStream) {
  18434. time_t timeout = 2000;
  18435. time_t threshold = 200;
  18436. Server svr;
  18437. Client cli("localhost", PORT);
  18438. max_timeout_test(svr, cli, timeout, threshold);
  18439. }
  18440. #ifdef CPPHTTPLIB_SSL_ENABLED
  18441. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18442. time_t timeout = 2000;
  18443. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18445. SSLClient cli("localhost", PORT);
  18446. cli.enable_server_certificate_verification(false);
  18447. max_timeout_test(svr, cli, timeout, threshold);
  18448. }
  18449. #endif
  18450. class EventDispatcher {
  18451. public:
  18452. EventDispatcher() {}
  18453. bool wait_event(DataSink *sink) {
  18454. unique_lock<mutex> lk(m_);
  18455. int id = id_;
  18456. // Wait with timeout to prevent hanging if client disconnects
  18457. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18458. [&] { return cid_ == id; })) {
  18459. return false; // Timeout occurred
  18460. }
  18461. sink->write(message_.data(), message_.size());
  18462. return true;
  18463. }
  18464. void send_event(const string &message) {
  18465. lock_guard<mutex> lk(m_);
  18466. cid_ = id_++;
  18467. message_ = message;
  18468. cv_.notify_all();
  18469. }
  18470. private:
  18471. mutex m_;
  18472. condition_variable cv_;
  18473. atomic_int id_{0};
  18474. atomic_int cid_{-1};
  18475. string message_;
  18476. };
  18477. TEST(ClientInThreadTest, Issue2068) {
  18478. EventDispatcher ed;
  18479. Server svr;
  18480. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18481. res.set_chunked_content_provider("text/event-stream",
  18482. [&](size_t /*offset*/, DataSink &sink) {
  18483. return ed.wait_event(&sink);
  18484. });
  18485. });
  18486. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18487. svr.wait_until_ready();
  18488. thread event_thread([&] {
  18489. int id = 0;
  18490. while (svr.is_running()) {
  18491. this_thread::sleep_for(chrono::milliseconds(500));
  18492. std::stringstream ss;
  18493. ss << "data: " << id << "\n\n";
  18494. ed.send_event(ss.str());
  18495. id++;
  18496. }
  18497. });
  18498. auto se = detail::scope_exit([&] {
  18499. svr.stop();
  18500. listen_thread.join();
  18501. event_thread.join();
  18502. ASSERT_FALSE(svr.is_running());
  18503. });
  18504. {
  18505. auto client = detail::make_unique<Client>(HOST, PORT);
  18506. client->set_read_timeout(std::chrono::minutes(10));
  18507. std::atomic<bool> stop{false};
  18508. std::thread t([&] {
  18509. client->Get("/event1",
  18510. [&](const char *, size_t) -> bool { return !stop; });
  18511. });
  18512. std::this_thread::sleep_for(std::chrono::seconds(2));
  18513. stop = true;
  18514. client->stop();
  18515. t.join();
  18516. // Reset client after thread has finished
  18517. client.reset();
  18518. }
  18519. }
  18520. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18521. auto handled = false;
  18522. Server svr;
  18523. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18525. auto se = detail::scope_exit([&] {
  18526. svr.stop();
  18527. t.join();
  18528. ASSERT_FALSE(svr.is_running());
  18529. ASSERT_FALSE(handled);
  18530. });
  18531. svr.wait_until_ready();
  18532. // Two Content-Length headers with different values — must be rejected
  18533. auto req = "POST /test HTTP/1.1\r\n"
  18534. "Content-Length: 5\r\n"
  18535. "Content-Length: 10\r\n"
  18536. "\r\n"
  18537. "hello";
  18538. std::string response;
  18539. ASSERT_TRUE(send_request(1, req, &response));
  18540. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18541. response.substr(0, response.find("\r\n")));
  18542. }
  18543. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18544. auto handled = false;
  18545. Server svr;
  18546. svr.Post("/test", [&](const Request &, Response &res) {
  18547. handled = true;
  18548. res.set_content("ok", "text/plain");
  18549. });
  18550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. t.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. ASSERT_TRUE(handled);
  18556. });
  18557. svr.wait_until_ready();
  18558. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18559. auto req = "POST /test HTTP/1.1\r\n"
  18560. "Host: localhost\r\n"
  18561. "Content-Length: 5\r\n"
  18562. "Content-Length: 5\r\n"
  18563. "\r\n"
  18564. "hello";
  18565. std::string response;
  18566. ASSERT_TRUE(send_request(1, req, &response));
  18567. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18568. }
  18569. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18570. Server svr;
  18571. svr.Get("/test", [](const Request &, Response &res) {
  18572. res.set_content("ok", "text/plain");
  18573. });
  18574. auto port = svr.bind_to_any_port(HOST);
  18575. thread t = thread([&] { svr.listen_after_bind(); });
  18576. auto se = detail::scope_exit([&] {
  18577. svr.stop();
  18578. t.join();
  18579. ASSERT_FALSE(svr.is_running());
  18580. });
  18581. svr.wait_until_ready();
  18582. auto status_line = [&](const std::string &host_lines) {
  18583. std::string res;
  18584. send_request(
  18585. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18586. &res, port);
  18587. return res.substr(0, res.find("\r\n"));
  18588. };
  18589. const char *accepted[] = {
  18590. "Host: localhost\r\n",
  18591. "Host: a.example:8080\r\n",
  18592. "Host: my_service\r\n",
  18593. "Host: [::1]:8080\r\n",
  18594. "Host: [fe80::1%25eth0]\r\n",
  18595. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18596. };
  18597. for (auto host_lines : accepted) {
  18598. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18599. }
  18600. const char *rejected[] = {
  18601. "Host: a.example\r\nHost: b.example\r\n",
  18602. "Host: a.example\r\nHost: a.example\r\n",
  18603. "Host: a@b.example\r\n",
  18604. "Host: a.example/b\r\n",
  18605. "Host: a.example\\b\r\n",
  18606. "Host: a.example?b\r\n",
  18607. "Host: a.example#b\r\n",
  18608. "Host: a.example b.example\r\n",
  18609. };
  18610. for (auto host_lines : rejected) {
  18611. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18612. << host_lines;
  18613. }
  18614. }
  18615. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18616. Server svr;
  18617. svr.Get("/", [](const Request &req, Response &res) {
  18618. EXPECT_EQ(2U, req.trailers.size());
  18619. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18620. // Denied
  18621. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18622. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18623. // Accepted
  18624. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18625. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18626. EXPECT_TRUE(req.has_trailer("X-World"));
  18627. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18628. res.set_content("ok", "text/plain");
  18629. });
  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. });
  18636. svr.wait_until_ready();
  18637. const std::string req = "GET / HTTP/1.1\r\n"
  18638. "Transfer-Encoding: chunked\r\n"
  18639. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18640. "\r\n"
  18641. "0\r\n"
  18642. "Content-Length: 10\r\n"
  18643. "Host: internal.local\r\n"
  18644. "Content-Type: malicious/content\r\n"
  18645. "Cookie: any\r\n"
  18646. "Set-Cookie: any\r\n"
  18647. "X-Forwarded-For: attacker.com\r\n"
  18648. "X-Real-Ip: 1.1.1.1\r\n"
  18649. "X-Hello: hello\r\n"
  18650. "X-World: world\r\n"
  18651. "\r\n";
  18652. std::string res;
  18653. ASSERT_TRUE(send_request(1, req, &res));
  18654. }
  18655. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18656. // several field lines, and the combined value is what has to be parsed. A
  18657. // Trailer field split across lines therefore declares every name it lists;
  18658. // reading only the first line silently drops the trailers the later lines
  18659. // declare. The prohibited-trailer filter still applies to every line.
  18660. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18661. Server svr;
  18662. size_t observed_trailer_count = 0;
  18663. std::string observed_hello;
  18664. std::string observed_world;
  18665. bool observed_content_length = true;
  18666. svr.Get("/", [&](const Request &req, Response &res) {
  18667. observed_trailer_count = req.trailers.size();
  18668. observed_hello = req.get_trailer_value("X-Hello");
  18669. observed_world = req.get_trailer_value("X-World");
  18670. observed_content_length = req.has_trailer("Content-Length");
  18671. res.set_content("ok", "text/plain");
  18672. });
  18673. auto port = svr.bind_to_any_port(HOST);
  18674. thread t = thread([&]() { svr.listen_after_bind(); });
  18675. auto se = detail::scope_exit([&] {
  18676. svr.stop();
  18677. t.join();
  18678. ASSERT_FALSE(svr.is_running());
  18679. });
  18680. svr.wait_until_ready();
  18681. const std::string req = "GET / HTTP/1.1\r\n"
  18682. "Host: localhost\r\n"
  18683. "Transfer-Encoding: chunked\r\n"
  18684. "Trailer: X-Hello\r\n"
  18685. "Trailer: X-World, Content-Length\r\n"
  18686. "\r\n"
  18687. "0\r\n"
  18688. "X-Hello: hello\r\n"
  18689. "X-World: world\r\n"
  18690. "Content-Length: 10\r\n"
  18691. "\r\n";
  18692. std::string res;
  18693. ASSERT_TRUE(send_request(1, req, &res, port));
  18694. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18695. // Accepted: both field lines contribute to the declared set
  18696. EXPECT_EQ(2U, observed_trailer_count);
  18697. EXPECT_EQ(observed_hello, "hello");
  18698. EXPECT_EQ(observed_world, "world");
  18699. // Denied: a prohibited name stays prohibited on a later field line
  18700. EXPECT_FALSE(observed_content_length);
  18701. }
  18702. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18703. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18704. // unbounded run of fields that are never declared, because the counter would
  18705. // only advance for declared fields.
  18706. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18707. Server svr;
  18708. bool handler_called = false;
  18709. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18710. handler_called = true;
  18711. res.set_content("ok", "text/plain");
  18712. });
  18713. auto port = svr.bind_to_any_port(HOST);
  18714. thread t = thread([&]() { svr.listen_after_bind(); });
  18715. auto se = detail::scope_exit([&] {
  18716. svr.stop();
  18717. t.join();
  18718. ASSERT_FALSE(svr.is_running());
  18719. });
  18720. svr.wait_until_ready();
  18721. // Declare nothing, then send far more undeclared trailer fields than the
  18722. // header-count limit. Parsing must stop and reject the request rather than
  18723. // read every line.
  18724. std::string req = "GET / HTTP/1.1\r\n"
  18725. "Transfer-Encoding: chunked\r\n"
  18726. "\r\n"
  18727. "0\r\n";
  18728. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18729. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18730. }
  18731. req += "\r\n";
  18732. std::string res;
  18733. ASSERT_TRUE(send_request(1, req, &res, port));
  18734. // The request is rejected before the handler runs.
  18735. EXPECT_FALSE(handler_called);
  18736. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18737. }
  18738. // The set of declared trailer names is capped so a peer cannot grow it without
  18739. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18740. // declared past the cap is not honored, even if the field is actually sent.
  18741. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18742. Server svr;
  18743. // One name inside the cap and one past it, so the test tracks the cap rather
  18744. // than a fixed count.
  18745. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18746. const std::string within_cap_name = "X-T-0";
  18747. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18748. bool observed_within_cap = false;
  18749. bool observed_past_cap = false;
  18750. svr.Get("/", [&](const Request &req, Response &res) {
  18751. observed_within_cap = req.has_trailer(within_cap_name);
  18752. observed_past_cap = req.has_trailer(past_cap_name);
  18753. res.set_content("ok", "text/plain");
  18754. });
  18755. auto port = svr.bind_to_any_port(HOST);
  18756. thread t = thread([&]() { svr.listen_after_bind(); });
  18757. auto se = detail::scope_exit([&] {
  18758. svr.stop();
  18759. t.join();
  18760. ASSERT_FALSE(svr.is_running());
  18761. });
  18762. svr.wait_until_ready();
  18763. // Declare more trailer names than the cap in a single Trailer field, then
  18764. // actually send the first (within the cap) and the last (past it).
  18765. std::string trailer_decl = "Trailer: ";
  18766. for (int i = 0; i < declared_count; i++) {
  18767. if (i != 0) { trailer_decl += ", "; }
  18768. trailer_decl += "X-T-" + std::to_string(i);
  18769. }
  18770. trailer_decl += "\r\n";
  18771. const std::string req = "GET / HTTP/1.1\r\n"
  18772. "Host: localhost\r\n"
  18773. "Transfer-Encoding: chunked\r\n" +
  18774. trailer_decl +
  18775. "\r\n"
  18776. "0\r\n" +
  18777. within_cap_name + ": a\r\n" + past_cap_name +
  18778. ": b\r\n"
  18779. "\r\n";
  18780. std::string res;
  18781. ASSERT_TRUE(send_request(1, req, &res, port));
  18782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18783. // A name within the cap is honored; one declared past the cap is dropped.
  18784. EXPECT_TRUE(observed_within_cap);
  18785. EXPECT_FALSE(observed_past_cap);
  18786. }
  18787. // A direct client that is not listed in trusted_proxies must not be able to
  18788. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18789. // the peer address on the actual TCP connection determines whether the
  18790. // header is honored.
  18791. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18792. Server svr;
  18793. // Deliberately does NOT include the loopback address the test client
  18794. // actually connects from, so the direct connection is not a trusted proxy.
  18795. svr.set_trusted_proxies({"203.0.113.66"});
  18796. std::string observed_remote_addr;
  18797. svr.Get("/ip", [&](const Request &req, Response &res) {
  18798. observed_remote_addr = req.remote_addr;
  18799. res.set_content("ok", "text/plain");
  18800. });
  18801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18802. auto se = detail::scope_exit([&] {
  18803. svr.stop();
  18804. t.join();
  18805. ASSERT_FALSE(svr.is_running());
  18806. });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18811. EXPECT_EQ(StatusCode::OK_200, res->status);
  18812. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18813. // ignored entirely and the real connection-level address retained.
  18814. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18815. observed_remote_addr == "127.0.0.1");
  18816. }
  18817. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18818. Server svr;
  18819. std::string observed_remote_addr;
  18820. std::string observed_xff;
  18821. svr.Get("/ip", [&](const Request &req, Response &res) {
  18822. observed_remote_addr = req.remote_addr;
  18823. observed_xff = req.get_header_value("X-Forwarded-For");
  18824. res.set_content("ok", "text/plain");
  18825. });
  18826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18827. auto se = detail::scope_exit([&] {
  18828. svr.stop();
  18829. t.join();
  18830. ASSERT_FALSE(svr.is_running());
  18831. });
  18832. svr.wait_until_ready();
  18833. Client cli(HOST, PORT);
  18834. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18836. EXPECT_EQ(StatusCode::OK_200, res->status);
  18837. EXPECT_EQ(observed_xff, "203.0.113.66");
  18838. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18839. observed_remote_addr == "127.0.0.1");
  18840. }
  18841. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18842. Server svr;
  18843. svr.set_trusted_proxies({"203.0.113.66"});
  18844. std::string observed_remote_addr;
  18845. std::string observed_xff;
  18846. svr.Get("/ip", [&](const Request &req, Response &res) {
  18847. observed_remote_addr = req.remote_addr;
  18848. observed_xff = req.get_header_value("X-Forwarded-For");
  18849. res.set_content("ok", "text/plain");
  18850. });
  18851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18852. auto se = detail::scope_exit([&] {
  18853. svr.stop();
  18854. t.join();
  18855. ASSERT_FALSE(svr.is_running());
  18856. });
  18857. svr.wait_until_ready();
  18858. Client cli(HOST, PORT);
  18859. auto res = cli.Get("/ip");
  18860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18861. EXPECT_EQ(StatusCode::OK_200, res->status);
  18862. EXPECT_EQ(observed_xff, "");
  18863. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18864. observed_remote_addr == "127.0.0.1");
  18865. }
  18866. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18867. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18868. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18869. Server svr;
  18870. svr.set_trusted_proxies({"127.0.0.1"});
  18871. svr.Get("/ip", [](const Request &req, Response &res) {
  18872. res.set_content(req.remote_addr, "text/plain");
  18873. });
  18874. auto port = svr.bind_to_any_port("::");
  18875. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18876. thread t = thread([&] { svr.listen_after_bind(); });
  18877. auto se = detail::scope_exit([&] {
  18878. svr.stop();
  18879. t.join();
  18880. ASSERT_FALSE(svr.is_running());
  18881. });
  18882. svr.wait_until_ready();
  18883. Client cli("127.0.0.1", port);
  18884. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18886. EXPECT_EQ("198.51.100.23", res->body);
  18887. }
  18888. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18889. Server svr;
  18890. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18891. svr.Get("/ip", [](const Request &req, Response &res) {
  18892. res.set_content(req.remote_addr, "text/plain");
  18893. });
  18894. auto port = svr.bind_to_any_port(HOST);
  18895. ASSERT_GT(port, 0);
  18896. thread t = thread([&] { svr.listen_after_bind(); });
  18897. auto se = detail::scope_exit([&] {
  18898. svr.stop();
  18899. t.join();
  18900. ASSERT_FALSE(svr.is_running());
  18901. });
  18902. svr.wait_until_ready();
  18903. Client cli(HOST, port);
  18904. auto res = cli.Get(
  18905. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18907. EXPECT_EQ("198.51.100.23", res->body);
  18908. }
  18909. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18910. Server svr;
  18911. // Include the loopback address the test client actually connects from, so
  18912. // the direct connection itself is recognized as the trusted proxy hop.
  18913. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18914. std::string observed_remote_addr;
  18915. std::string observed_xff;
  18916. svr.Get("/ip", [&](const Request &req, Response &res) {
  18917. observed_remote_addr = req.remote_addr;
  18918. observed_xff = req.get_header_value("X-Forwarded-For");
  18919. res.set_content("ok", "text/plain");
  18920. });
  18921. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. Client cli(HOST, PORT);
  18929. auto res = cli.Get(
  18930. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18932. EXPECT_EQ(StatusCode::OK_200, res->status);
  18933. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18934. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18935. }
  18936. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18937. Server svr;
  18938. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18939. std::string observed_remote_addr;
  18940. std::string observed_xff;
  18941. svr.Get("/ip", [&](const Request &req, Response &res) {
  18942. observed_remote_addr = req.remote_addr;
  18943. observed_xff = req.get_header_value("X-Forwarded-For");
  18944. res.set_content("ok", "text/plain");
  18945. });
  18946. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18947. auto se = detail::scope_exit([&] {
  18948. svr.stop();
  18949. t.join();
  18950. ASSERT_FALSE(svr.is_running());
  18951. });
  18952. svr.wait_until_ready();
  18953. Client cli(HOST, PORT);
  18954. auto res = cli.Get(
  18955. "/ip",
  18956. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18958. EXPECT_EQ(StatusCode::OK_200, res->status);
  18959. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18960. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18961. }
  18962. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18963. Server svr;
  18964. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18965. std::string observed_remote_addr;
  18966. std::string observed_xff;
  18967. svr.Get("/ip", [&](const Request &req, Response &res) {
  18968. observed_remote_addr = req.remote_addr;
  18969. observed_xff = req.get_header_value("X-Forwarded-For");
  18970. res.set_content("ok", "text/plain");
  18971. });
  18972. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18973. auto se = detail::scope_exit([&] {
  18974. svr.stop();
  18975. t.join();
  18976. ASSERT_FALSE(svr.is_running());
  18977. });
  18978. svr.wait_until_ready();
  18979. Client cli(HOST, PORT);
  18980. auto res = cli.Get(
  18981. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18983. EXPECT_EQ(StatusCode::OK_200, res->status);
  18984. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18985. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18986. // and must not be selected.
  18987. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18988. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18989. }
  18990. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18991. Server svr;
  18992. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18993. std::string observed_remote_addr;
  18994. svr.Get("/ip", [&](const Request &req, Response &res) {
  18995. observed_remote_addr = req.remote_addr;
  18996. res.set_content("ok", "text/plain");
  18997. });
  18998. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18999. auto se = detail::scope_exit([&] {
  19000. svr.stop();
  19001. t.join();
  19002. ASSERT_FALSE(svr.is_running());
  19003. });
  19004. svr.wait_until_ready();
  19005. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19006. // a forged address and the trusted proxy's own address; the forged value must
  19007. // not win over the address the trusted proxy actually recorded.
  19008. Client cli(HOST, PORT);
  19009. auto res = cli.Get(
  19010. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19012. EXPECT_EQ(StatusCode::OK_200, res->status);
  19013. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19014. }
  19015. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19016. Server svr;
  19017. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19018. std::string observed_remote_addr;
  19019. std::string observed_xff;
  19020. svr.Get("/ip", [&](const Request &req, Response &res) {
  19021. observed_remote_addr = req.remote_addr;
  19022. observed_xff = req.get_header_value("X-Forwarded-For");
  19023. res.set_content("ok", "text/plain");
  19024. });
  19025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19026. auto se = detail::scope_exit([&] {
  19027. svr.stop();
  19028. t.join();
  19029. ASSERT_FALSE(svr.is_running());
  19030. });
  19031. svr.wait_until_ready();
  19032. Client cli(HOST, PORT);
  19033. auto res = cli.Get(
  19034. "/ip",
  19035. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19037. EXPECT_EQ(StatusCode::OK_200, res->status);
  19038. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19039. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19040. }
  19041. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19042. Server svr;
  19043. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19044. std::string observed_remote_addr;
  19045. std::string observed_xff;
  19046. svr.Get("/ip", [&](const Request &req, Response &res) {
  19047. observed_remote_addr = req.remote_addr;
  19048. observed_xff = req.get_header_value("X-Forwarded-For");
  19049. res.set_content("ok", "text/plain");
  19050. });
  19051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19052. auto se = detail::scope_exit([&] {
  19053. svr.stop();
  19054. t.join();
  19055. ASSERT_FALSE(svr.is_running());
  19056. });
  19057. svr.wait_until_ready();
  19058. std::string raw_req =
  19059. "GET /ip HTTP/1.1\r\n"
  19060. "Host: localhost\r\n"
  19061. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19062. "Connection: close\r\n"
  19063. "\r\n";
  19064. std::string out;
  19065. ASSERT_TRUE(send_request(5, raw_req, &out));
  19066. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19067. // Header parser trims surrounding whitespace of the header value
  19068. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19069. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19070. }
  19071. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19072. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19073. // their own X-Forwarded-For as a separate field line rather than extending the
  19074. // one the client sent, so every occurrence has to be taken into account.
  19075. // Reading only the first one hands back the address the client chose.
  19076. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19077. Server svr;
  19078. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19079. std::string observed_remote_addr;
  19080. size_t observed_xff_count = 0;
  19081. svr.Get("/ip", [&](const Request &req, Response &res) {
  19082. observed_remote_addr = req.remote_addr;
  19083. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19084. res.set_content("ok", "text/plain");
  19085. });
  19086. auto port = svr.bind_to_any_port(HOST);
  19087. thread t = thread([&]() { svr.listen_after_bind(); });
  19088. auto se = detail::scope_exit([&] {
  19089. svr.stop();
  19090. t.join();
  19091. ASSERT_FALSE(svr.is_running());
  19092. });
  19093. svr.wait_until_ready();
  19094. // The client supplies the first field line; the trusted proxy appends the
  19095. // address it observed as a second one.
  19096. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19097. "Host: localhost\r\n"
  19098. "X-Forwarded-For: 1.2.3.4\r\n"
  19099. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19100. "Connection: close\r\n"
  19101. "\r\n";
  19102. std::string out;
  19103. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19104. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19105. EXPECT_EQ(observed_xff_count, 2U);
  19106. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19107. // The same chain spread over one field line per hop derives the same client
  19108. // address, i.e. the split and the comma-joined representations agree.
  19109. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19110. "Host: localhost\r\n"
  19111. "X-Forwarded-For: 1.2.3.4\r\n"
  19112. "X-Forwarded-For: 198.51.100.23\r\n"
  19113. "X-Forwarded-For: 192.0.2.45\r\n"
  19114. "Connection: close\r\n"
  19115. "\r\n";
  19116. out.clear();
  19117. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19118. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19119. EXPECT_EQ(observed_xff_count, 3U);
  19120. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19121. }
  19122. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19123. // crash the server (it used to call front() on an empty vector inside
  19124. // get_client_ip). The connection-level remote address must be retained instead.
  19125. static void run_malformed_xff_test(const std::string &xff_value) {
  19126. Server svr;
  19127. svr.set_trusted_proxies({"192.0.2.45"});
  19128. std::string observed_remote_addr;
  19129. svr.Get("/ip", [&](const Request &req, Response &res) {
  19130. observed_remote_addr = req.remote_addr;
  19131. res.set_content("ok", "text/plain");
  19132. });
  19133. int port = 0;
  19134. thread t = thread([&]() {
  19135. port = svr.bind_to_any_port(HOST);
  19136. svr.listen_after_bind();
  19137. });
  19138. auto se = detail::scope_exit([&] {
  19139. svr.stop();
  19140. t.join();
  19141. ASSERT_FALSE(svr.is_running());
  19142. });
  19143. svr.wait_until_ready();
  19144. Client cli(HOST, port);
  19145. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19147. EXPECT_EQ(StatusCode::OK_200, res->status);
  19148. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19149. observed_remote_addr == "127.0.0.1");
  19150. }
  19151. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19152. run_malformed_xff_test("");
  19153. }
  19154. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19155. run_malformed_xff_test(",");
  19156. }
  19157. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19158. run_malformed_xff_test(", , ,");
  19159. }
  19160. // The same rule applies to Accept: a request whose acceptable types are spread
  19161. // over several field lines must be negotiated against all of them.
  19162. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19163. // case-insensitive connection options. Comparing the whole field value against
  19164. // one option misses a client that sends several of them, and misses every
  19165. // casing but the one written in the comparison.
  19166. //
  19167. // Sends req, reads the response, then reuses the same socket for a second
  19168. // request to find out whether the server kept the connection.
  19169. static void probe_connection_reuse(int port, const std::string &req,
  19170. bool *announced_close, bool *reusable) {
  19171. auto error = Error::Success;
  19172. auto sock = detail::create_client_socket(
  19173. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19174. /*connection_timeout_sec=*/5, 0,
  19175. /*read_timeout_sec=*/1, 0,
  19176. /*write_timeout_sec=*/5, 0, std::string(), error);
  19177. ASSERT_NE(sock, INVALID_SOCKET);
  19178. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19179. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19180. "Host: localhost\r\n"
  19181. "Connection: close\r\n"
  19182. "\r\n";
  19183. std::string first_response;
  19184. std::string second_response;
  19185. detail::process_client_socket(
  19186. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19187. [&](Stream &strm) {
  19188. if (strm.write(req.data(), req.size()) !=
  19189. static_cast<ssize_t>(req.size())) {
  19190. return false;
  19191. }
  19192. char buf[512];
  19193. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19194. // Headers plus the two-byte body of the handler below
  19195. while (reader.getline()) {
  19196. first_response += reader.ptr();
  19197. if (first_response.find("ok") != std::string::npos) { break; }
  19198. }
  19199. if (strm.write(second.data(), second.size()) !=
  19200. static_cast<ssize_t>(second.size())) {
  19201. return true;
  19202. }
  19203. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19204. while (reader2.getline()) {
  19205. second_response += reader2.ptr();
  19206. if (second_response.find("ok") != std::string::npos) { break; }
  19207. }
  19208. return true;
  19209. });
  19210. *announced_close =
  19211. first_response.find("Connection: close") != std::string::npos;
  19212. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19213. }
  19214. class ConnectionTokenTest : public ::testing::Test {
  19215. protected:
  19216. void SetUp() override {
  19217. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19218. res.set_content("ok", "text/plain");
  19219. });
  19220. port_ = svr_.bind_to_any_port(HOST);
  19221. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19222. svr_.wait_until_ready();
  19223. }
  19224. void TearDown() override {
  19225. svr_.stop();
  19226. if (thread_.joinable()) { thread_.join(); }
  19227. }
  19228. Server svr_;
  19229. int port_ = 0;
  19230. thread thread_;
  19231. };
  19232. // "close" alongside another option still closes the connection, and the
  19233. // response says so rather than leaving the peer to discover it.
  19234. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19235. bool announced_close = false;
  19236. bool reusable = true;
  19237. probe_connection_reuse(port_,
  19238. "GET /keepalive HTTP/1.1\r\n"
  19239. "Host: localhost\r\n"
  19240. "Connection: keep-alive, close\r\n"
  19241. "\r\n",
  19242. &announced_close, &reusable);
  19243. EXPECT_TRUE(announced_close);
  19244. EXPECT_FALSE(reusable);
  19245. }
  19246. // "close" split over two field lines is the same list, so it is honored too.
  19247. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19248. bool announced_close = false;
  19249. bool reusable = true;
  19250. probe_connection_reuse(port_,
  19251. "GET /keepalive HTTP/1.1\r\n"
  19252. "Host: localhost\r\n"
  19253. "Connection: keep-alive\r\n"
  19254. "Connection: close\r\n"
  19255. "\r\n",
  19256. &announced_close, &reusable);
  19257. EXPECT_TRUE(announced_close);
  19258. EXPECT_FALSE(reusable);
  19259. }
  19260. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19261. // keep-alive in the spelling everyone actually sends keeps its connection.
  19262. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19263. bool announced_close = false;
  19264. bool reusable = false;
  19265. probe_connection_reuse(port_,
  19266. "GET /keepalive HTTP/1.0\r\n"
  19267. "Host: localhost\r\n"
  19268. "Connection: keep-alive\r\n"
  19269. "\r\n",
  19270. &announced_close, &reusable);
  19271. EXPECT_FALSE(announced_close);
  19272. EXPECT_TRUE(reusable);
  19273. }
  19274. // A token the value merely contains is not the token itself.
  19275. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19276. bool announced_close = false;
  19277. bool reusable = false;
  19278. probe_connection_reuse(port_,
  19279. "GET /keepalive HTTP/1.1\r\n"
  19280. "Host: localhost\r\n"
  19281. "Connection: notclose\r\n"
  19282. "\r\n",
  19283. &announced_close, &reusable);
  19284. EXPECT_FALSE(announced_close);
  19285. EXPECT_TRUE(reusable);
  19286. }
  19287. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19288. Server svr;
  19289. std::vector<std::string> observed_types;
  19290. svr.Get("/", [&](const Request &req, Response &res) {
  19291. observed_types = req.accept_content_types;
  19292. res.set_content("ok", "text/plain");
  19293. });
  19294. auto port = svr.bind_to_any_port(HOST);
  19295. thread t = thread([&]() { svr.listen_after_bind(); });
  19296. auto se = detail::scope_exit([&] {
  19297. svr.stop();
  19298. t.join();
  19299. ASSERT_FALSE(svr.is_running());
  19300. });
  19301. svr.wait_until_ready();
  19302. Client cli(HOST, port);
  19303. Headers headers;
  19304. headers.emplace("Accept", "text/plain;q=0.5");
  19305. headers.emplace("Accept", "application/json");
  19306. auto res = cli.Get("/", headers);
  19307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19308. EXPECT_EQ(StatusCode::OK_200, res->status);
  19309. // Sorted by q-value, so the second field line's type comes first
  19310. ASSERT_EQ(2U, observed_types.size());
  19311. EXPECT_EQ("application/json", observed_types[0]);
  19312. EXPECT_EQ("text/plain", observed_types[1]);
  19313. }
  19314. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19315. // empty field line must not contribute a bare comma to the combined value.
  19316. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19317. Server svr;
  19318. std::vector<std::string> observed_types;
  19319. svr.Get("/", [&](const Request &req, Response &res) {
  19320. observed_types = req.accept_content_types;
  19321. res.set_content("ok", "text/plain");
  19322. });
  19323. auto port = svr.bind_to_any_port(HOST);
  19324. thread t = thread([&]() { svr.listen_after_bind(); });
  19325. auto se = detail::scope_exit([&] {
  19326. svr.stop();
  19327. t.join();
  19328. ASSERT_FALSE(svr.is_running());
  19329. });
  19330. svr.wait_until_ready();
  19331. // Empty first field line, then a real one
  19332. std::string raw_req = "GET / HTTP/1.1\r\n"
  19333. "Host: localhost\r\n"
  19334. "Accept:\r\n"
  19335. "Accept: application/json\r\n"
  19336. "Connection: close\r\n"
  19337. "\r\n";
  19338. std::string out;
  19339. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19340. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19341. ASSERT_EQ(1U, observed_types.size());
  19342. EXPECT_EQ("application/json", observed_types[0]);
  19343. }
  19344. // The skip in get_combined_header_value() is what keeps an empty field line
  19345. // from contributing a bare comma. Only a trailing empty field line exercises
  19346. // it: a leading one is already covered by the "combined is still empty" check,
  19347. // and parse_accept_header() now ignores the empty element either way, so the
  19348. // request-level test above can no longer tell the two apart.
  19349. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19350. Headers headers;
  19351. headers.emplace("Accept", "text/html");
  19352. headers.emplace("Accept", "");
  19353. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19354. headers.clear();
  19355. headers.emplace("Accept", "");
  19356. headers.emplace("Accept", "application/json");
  19357. EXPECT_EQ("application/json",
  19358. detail::get_combined_header_value(headers, "Accept"));
  19359. }
  19360. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19361. // An encoding offered on a later Accept-Encoding field line is still offered.
  19362. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19363. Server svr;
  19364. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19365. res.set_content(std::string(1024, 'x'), "text/plain");
  19366. });
  19367. auto port = svr.bind_to_any_port(HOST);
  19368. thread t = thread([&]() { svr.listen_after_bind(); });
  19369. auto se = detail::scope_exit([&] {
  19370. svr.stop();
  19371. t.join();
  19372. ASSERT_FALSE(svr.is_running());
  19373. });
  19374. svr.wait_until_ready();
  19375. Client cli(HOST, port);
  19376. cli.set_decompress(false);
  19377. Headers headers;
  19378. headers.emplace("Accept-Encoding", "identity");
  19379. headers.emplace("Accept-Encoding", "gzip");
  19380. auto res = cli.Get("/", headers);
  19381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19382. EXPECT_EQ(StatusCode::OK_200, res->status);
  19383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19384. }
  19385. #endif
  19386. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19387. // Transfer-Encoding is not its body.
  19388. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19389. Server svr;
  19390. svr.set_payload_max_length(8);
  19391. svr.Post("/test", [](const Request &, Response &res) {
  19392. res.set_content("ok", "text/plain");
  19393. });
  19394. auto port = svr.bind_to_any_port(HOST);
  19395. ASSERT_GT(port, 0);
  19396. thread t = thread([&] { svr.listen_after_bind(); });
  19397. auto se = detail::scope_exit([&] {
  19398. svr.stop();
  19399. t.join();
  19400. ASSERT_FALSE(svr.is_running());
  19401. });
  19402. svr.wait_until_ready();
  19403. std::string resp;
  19404. ASSERT_TRUE(send_request(1,
  19405. "POST /test HTTP/1.1\r\n"
  19406. "Host: localhost\r\n"
  19407. "Connection: close\r\n"
  19408. "\r\n" +
  19409. std::string(16, 'X'),
  19410. &resp, port));
  19411. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19412. }
  19413. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19414. Server svr;
  19415. svr.Post("/post", [&](const Request &req, Response &res) {
  19416. res.set_content(req.body, "text/plain");
  19417. });
  19418. svr.Put("/put", [&](const Request &req, Response &res) {
  19419. res.set_content(req.body, "text/plain");
  19420. });
  19421. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19422. res.set_content(req.body, "text/plain");
  19423. });
  19424. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19425. res.set_content(req.body, "text/plain");
  19426. });
  19427. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19428. auto se = detail::scope_exit([&] {
  19429. svr.stop();
  19430. t.join();
  19431. ASSERT_FALSE(svr.is_running());
  19432. });
  19433. svr.wait_until_ready();
  19434. std::string resp;
  19435. // POST without Content-Length
  19436. ASSERT_TRUE(send_request(5,
  19437. "POST /post HTTP/1.1\r\n"
  19438. "Host: localhost\r\n"
  19439. "Connection: close\r\n"
  19440. "\r\n",
  19441. &resp));
  19442. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19443. // PUT without Content-Length
  19444. resp.clear();
  19445. ASSERT_TRUE(send_request(5,
  19446. "PUT /put HTTP/1.1\r\n"
  19447. "Host: localhost\r\n"
  19448. "Connection: close\r\n"
  19449. "\r\n",
  19450. &resp));
  19451. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19452. // PATCH without Content-Length
  19453. resp.clear();
  19454. ASSERT_TRUE(send_request(5,
  19455. "PATCH /patch HTTP/1.1\r\n"
  19456. "Host: localhost\r\n"
  19457. "Connection: close\r\n"
  19458. "\r\n",
  19459. &resp));
  19460. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19461. // DELETE without Content-Length
  19462. resp.clear();
  19463. ASSERT_TRUE(send_request(5,
  19464. "DELETE /delete HTTP/1.1\r\n"
  19465. "Host: localhost\r\n"
  19466. "Connection: close\r\n"
  19467. "\r\n",
  19468. &resp));
  19469. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19470. }
  19471. //==============================================================================
  19472. // open_stream() Tests
  19473. //==============================================================================
  19474. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19475. std::string result;
  19476. char buf[8192];
  19477. ssize_t n;
  19478. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19479. result.append(buf, static_cast<size_t>(n));
  19480. }
  19481. return result;
  19482. }
  19483. // Mock stream for unit tests
  19484. class MockStream : public Stream {
  19485. public:
  19486. std::string data;
  19487. size_t pos = 0;
  19488. ssize_t error_after = -1; // -1 = no error
  19489. explicit MockStream(const std::string &d, ssize_t err = -1)
  19490. : data(d), error_after(err) {}
  19491. bool is_readable() const override { return true; }
  19492. bool wait_readable() const override { return true; }
  19493. bool wait_writable() const override { return true; }
  19494. ssize_t read(char *ptr, size_t size) override {
  19495. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19496. if (pos >= data.size()) return 0;
  19497. size_t limit =
  19498. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19499. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19500. std::memcpy(ptr, data.data() + pos, to_read);
  19501. pos += to_read;
  19502. return static_cast<ssize_t>(to_read);
  19503. }
  19504. ssize_t write(const char *, size_t) override { return -1; }
  19505. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19506. ip = "127.0.0.1";
  19507. port = 0;
  19508. }
  19509. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19510. ip = "127.0.0.1";
  19511. port = 0;
  19512. }
  19513. socket_t socket() const override { return INVALID_SOCKET; }
  19514. time_t duration() const override { return 0; }
  19515. };
  19516. TEST(StreamHandleTest, Basic) {
  19517. ClientImpl::StreamHandle handle;
  19518. EXPECT_FALSE(handle.is_valid());
  19519. handle.response = detail::make_unique<Response>();
  19520. handle.error = Error::Connection;
  19521. EXPECT_FALSE(handle.is_valid());
  19522. handle.error = Error::Success;
  19523. EXPECT_TRUE(handle.is_valid());
  19524. }
  19525. TEST(BodyReaderTest, Basic) {
  19526. MockStream stream("Hello, World!");
  19527. detail::BodyReader reader;
  19528. reader.stream = &stream;
  19529. reader.content_length = 13;
  19530. char buf[32];
  19531. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19532. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19533. EXPECT_TRUE(reader.eof);
  19534. }
  19535. TEST(BodyReaderTest, NoStream) {
  19536. detail::BodyReader reader;
  19537. char buf[32];
  19538. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19539. EXPECT_EQ(Error::Connection, reader.last_error);
  19540. }
  19541. TEST(BodyReaderTest, Error) {
  19542. MockStream stream("Hello, World!", 5);
  19543. detail::BodyReader reader;
  19544. reader.stream = &stream;
  19545. reader.content_length = 13;
  19546. char buf[32];
  19547. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19548. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19549. EXPECT_EQ(Error::Read, reader.last_error);
  19550. }
  19551. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19552. // Mock-based StreamHandle tests relying on private internals are removed.
  19553. class OpenStreamTest : public ::testing::Test {
  19554. protected:
  19555. void SetUp() override {
  19556. svr_.Get("/hello", [](const Request &, Response &res) {
  19557. res.set_content("Hello World!", "text/plain");
  19558. });
  19559. svr_.Get("/large", [](const Request &, Response &res) {
  19560. res.set_content(std::string(10000, 'X'), "text/plain");
  19561. });
  19562. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19563. res.set_content("Hello World!", "image/jpeg");
  19564. res.set_header("Content-Encoding", "UTF-8");
  19565. });
  19566. svr_.Get("/chunked", [](const Request &, Response &res) {
  19567. res.set_chunked_content_provider("text/plain",
  19568. [](size_t offset, DataSink &sink) {
  19569. if (offset < 15) {
  19570. sink.write("chunk", 5);
  19571. return true;
  19572. }
  19573. sink.done();
  19574. return true;
  19575. });
  19576. });
  19577. svr_.Get("/compressible", [](const Request &, Response &res) {
  19578. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19579. DataSink &sink) {
  19580. if (offset < 100 * 1024) {
  19581. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19582. sink.write(chunk.data(), chunk.size());
  19583. return true;
  19584. }
  19585. sink.done();
  19586. return true;
  19587. });
  19588. });
  19589. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19590. [](const Request & /*req*/, Response &res) {
  19591. auto i = new int(0);
  19592. res.set_header("Trailer", "Content-Length, X-Allowed");
  19593. res.set_chunked_content_provider(
  19594. "text/plain",
  19595. [i](size_t /*offset*/, DataSink &sink) {
  19596. switch (*i) {
  19597. case 0: sink.os << "123"; break;
  19598. case 1: sink.os << "456"; break;
  19599. case 2: sink.os << "789"; break;
  19600. case 3: {
  19601. sink.done_with_trailer(
  19602. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19603. } break;
  19604. }
  19605. (*i)++;
  19606. return true;
  19607. },
  19608. [i](bool success) {
  19609. EXPECT_TRUE(success);
  19610. delete i;
  19611. });
  19612. });
  19613. // Echo headers endpoint for header-related tests
  19614. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19615. std::string body;
  19616. for (const auto &h : req.headers) {
  19617. body.append(h.first);
  19618. body.push_back(':');
  19619. body.append(h.second);
  19620. body.push_back('\n');
  19621. }
  19622. res.set_content(body, "text/plain");
  19623. });
  19624. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19625. std::string body;
  19626. for (const auto &h : req.headers) {
  19627. body.append(h.first);
  19628. body.push_back(':');
  19629. body.append(h.second);
  19630. body.push_back('\n');
  19631. }
  19632. res.set_content(body, "text/plain");
  19633. });
  19634. port_ = svr_.bind_to_any_port("127.0.0.1");
  19635. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19636. svr_.wait_until_ready();
  19637. }
  19638. void TearDown() override {
  19639. svr_.stop();
  19640. if (thread_.joinable()) thread_.join();
  19641. }
  19642. Server svr_;
  19643. std::thread thread_;
  19644. int port_ = 0;
  19645. };
  19646. TEST_F(OpenStreamTest, Basic) {
  19647. Client cli("127.0.0.1", port_);
  19648. auto handle = cli.open_stream("GET", "/hello");
  19649. EXPECT_TRUE(handle.is_valid());
  19650. EXPECT_EQ("Hello World!", read_all(handle));
  19651. }
  19652. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19653. Client cli("127.0.0.1", port_);
  19654. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19655. ASSERT_TRUE(handle.is_valid());
  19656. EXPECT_EQ("Hello World!", read_all(handle));
  19657. }
  19658. TEST_F(OpenStreamTest, SmallBuffer) {
  19659. Client cli("127.0.0.1", port_);
  19660. auto handle = cli.open_stream("GET", "/hello");
  19661. std::string result;
  19662. char buf[4];
  19663. ssize_t n;
  19664. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19665. result.append(buf, static_cast<size_t>(n));
  19666. EXPECT_EQ("Hello World!", result);
  19667. }
  19668. TEST_F(OpenStreamTest, DefaultHeaders) {
  19669. Client cli("127.0.0.1", port_);
  19670. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19671. {
  19672. auto handle = cli.open_stream("GET", "/echo-headers");
  19673. ASSERT_TRUE(handle.is_valid());
  19674. auto body = read_all(handle);
  19675. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19676. std::string::npos);
  19677. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19678. std::string::npos);
  19679. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19680. }
  19681. // open_stream POST with body and no explicit content_type should NOT add
  19682. // text/plain Content-Type (behavior differs from non-streaming path), but
  19683. // should include Content-Length
  19684. {
  19685. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19686. ASSERT_TRUE(handle.is_valid());
  19687. auto body = read_all(handle);
  19688. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19689. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19690. }
  19691. // open_stream POST with explicit Content-Type should preserve it
  19692. {
  19693. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19694. {{"Content-Type", "application/custom"}},
  19695. "{}", "application/custom");
  19696. ASSERT_TRUE(handle.is_valid());
  19697. auto body = read_all(handle);
  19698. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19699. }
  19700. // User-specified User-Agent must not be overwritten for stream API
  19701. {
  19702. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19703. {{"User-Agent", "MyAgent/1.2"}});
  19704. ASSERT_TRUE(handle.is_valid());
  19705. auto body = read_all(handle);
  19706. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19707. }
  19708. }
  19709. TEST_F(OpenStreamTest, Large) {
  19710. Client cli("127.0.0.1", port_);
  19711. auto handle = cli.open_stream("GET", "/large");
  19712. EXPECT_EQ(10000u, read_all(handle).size());
  19713. }
  19714. TEST_F(OpenStreamTest, ConnectionError) {
  19715. Client cli("127.0.0.1", 9999);
  19716. auto handle = cli.open_stream("GET", "/hello");
  19717. EXPECT_FALSE(handle.is_valid());
  19718. }
  19719. TEST_F(OpenStreamTest, Chunked) {
  19720. Client cli("127.0.0.1", port_);
  19721. auto handle = cli.open_stream("GET", "/chunked");
  19722. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19723. "Transfer-Encoding") == "chunked");
  19724. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19725. }
  19726. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19727. Client cli("127.0.0.1", port_);
  19728. auto handle =
  19729. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19730. ASSERT_TRUE(handle.is_valid());
  19731. // Consume body to allow trailers to be received/parsed
  19732. auto body = read_all(handle);
  19733. // Explicitly parse trailers (ensure trailers are available for assertion)
  19734. handle.parse_trailers_if_needed();
  19735. EXPECT_EQ(std::string("123456789"), body);
  19736. // The response should include a Trailer header declaring both names
  19737. ASSERT_TRUE(handle.response);
  19738. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19739. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19740. handle.response->get_header_value("Trailer"));
  19741. // Prohibited trailer must not be present
  19742. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19743. // Allowed trailer should be present
  19744. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19745. EXPECT_EQ(std::string("yes"),
  19746. handle.response->get_trailer_value("X-Allowed"));
  19747. // Verify trailers are NOT present as regular headers
  19748. EXPECT_EQ(std::string(""),
  19749. handle.response->get_header_value("Content-Length"));
  19750. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19751. }
  19752. // Accepts one connection on an OS-assigned port, which it hands over through
  19753. // port_promise, reads the request head and sends back response. after_send,
  19754. // if given, runs on the connection before it is closed.
  19755. static std::thread
  19756. serve_single_response(std::promise<int> &port_promise,
  19757. const std::string &response,
  19758. std::function<void(socket_t)> after_send = nullptr) {
  19759. return std::thread([&port_promise, response, after_send] {
  19760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19761. default_socket_options(srv);
  19762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19764. sockaddr_in addr{};
  19765. addr.sin_family = AF_INET;
  19766. addr.sin_port = htons(0); // Let OS assign a free port
  19767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19768. int opt = 1;
  19769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19770. #ifdef _WIN32
  19771. reinterpret_cast<const char *>(&opt),
  19772. #else
  19773. &opt,
  19774. #endif
  19775. sizeof(opt));
  19776. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19777. ::listen(srv, 1) != 0) {
  19778. port_promise.set_value(-1);
  19779. detail::close_socket(srv);
  19780. return;
  19781. }
  19782. socklen_t addr_len = sizeof(addr);
  19783. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19784. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19785. sockaddr_in cli_addr{};
  19786. socklen_t cli_len = sizeof(cli_addr);
  19787. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19788. if (cli != INVALID_SOCKET) {
  19789. // Read the complete HTTP request (until the blank line that terminates
  19790. // headers) before sending the response. If the server closes the socket
  19791. // while the client's request data is still unread in the kernel receive
  19792. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19793. // connection on both sides: it discards the client's receive buffer
  19794. // (which already holds our response) and causes any in-progress write on
  19795. // the client to fail with ECONNRESET. Reading all request data first
  19796. // ensures close() emits a graceful FIN.
  19797. {
  19798. char rbuf[256];
  19799. std::string req;
  19800. while (req.find("\r\n\r\n") == std::string::npos) {
  19801. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19802. if (n <= 0) { break; }
  19803. req.append(rbuf, static_cast<size_t>(n));
  19804. }
  19805. }
  19806. ::send(cli,
  19807. #ifdef _WIN32
  19808. static_cast<const char *>(response.c_str()),
  19809. static_cast<int>(response.size()),
  19810. #else
  19811. response.c_str(), response.size(),
  19812. #endif
  19813. 0);
  19814. if (after_send) { after_send(cli); }
  19815. detail::close_socket(cli);
  19816. }
  19817. detail::close_socket(srv);
  19818. });
  19819. }
  19820. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19821. #ifndef _WIN32
  19822. signal(SIGPIPE, SIG_IGN);
  19823. #endif
  19824. std::promise<int> port_promise;
  19825. auto port_future = port_promise.get_future();
  19826. auto server_thread =
  19827. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19828. "Content-Type: text/plain\r\n"
  19829. "Content-Length: not-a-number\r\n"
  19830. "Connection: close\r\n"
  19831. "\r\n"
  19832. "hello");
  19833. auto port = port_future.get();
  19834. ASSERT_GT(port, 0);
  19835. Client cli("127.0.0.1", port);
  19836. auto handle = cli.open_stream("GET", "/");
  19837. EXPECT_FALSE(handle.is_valid());
  19838. server_thread.join();
  19839. }
  19840. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19841. #ifndef _WIN32
  19842. signal(SIGPIPE, SIG_IGN);
  19843. #endif
  19844. std::promise<int> port_promise;
  19845. auto port_future = port_promise.get_future();
  19846. auto server_thread = serve_single_response(
  19847. port_promise, "HTTP/1.1 200 OK\r\n"
  19848. "Content-Type: text/plain\r\n"
  19849. "Content-Length: 99999999999999999999999999\r\n"
  19850. "Connection: close\r\n"
  19851. "\r\n"
  19852. "hello");
  19853. auto port = port_future.get();
  19854. ASSERT_GT(port, 0);
  19855. // Historically std::stoull would throw std::out_of_range here and crash
  19856. // the process, then parsing silently clamped to a bogus framing length and
  19857. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19858. // so the stream fails to open, matching the not-a-number case above. The
  19859. // process still must NOT terminate.
  19860. Client cli("127.0.0.1", port);
  19861. auto handle = cli.open_stream("GET", "/");
  19862. EXPECT_FALSE(handle.is_valid());
  19863. server_thread.join();
  19864. }
  19865. // Serves `response` to the single request `fn` makes with a fresh client.
  19866. template <typename Fn>
  19867. static void with_single_response(const std::string &response, Fn fn) {
  19868. #ifndef _WIN32
  19869. signal(SIGPIPE, SIG_IGN);
  19870. #endif
  19871. std::promise<int> port_promise;
  19872. auto port_future = port_promise.get_future();
  19873. auto server_thread = serve_single_response(port_promise, response);
  19874. auto se = detail::scope_exit([&] { server_thread.join(); });
  19875. auto port = port_future.get();
  19876. ASSERT_GT(port, 0);
  19877. Client cli("127.0.0.1", port);
  19878. fn(cli);
  19879. }
  19880. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19881. // Neither Content-Length nor chunked: the body ends at the close
  19882. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19883. "Connection: close\r\n"
  19884. "\r\n"
  19885. "hello";
  19886. with_single_response(close_delimited, [](Client &cli) {
  19887. auto handle = cli.open_stream("GET", "/");
  19888. ASSERT_TRUE(handle.is_valid());
  19889. EXPECT_EQ("hello", read_all(handle));
  19890. EXPECT_FALSE(handle.has_read_error());
  19891. });
  19892. // A close before the end of the Content-Length is still an error
  19893. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19894. "Content-Length: 10\r\n"
  19895. "\r\n"
  19896. "hello";
  19897. with_single_response(short_content_length, [](Client &cli) {
  19898. auto handle = cli.open_stream("GET", "/");
  19899. ASSERT_TRUE(handle.is_valid());
  19900. read_all(handle);
  19901. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19902. });
  19903. // So is a close before the last chunk
  19904. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19905. "Transfer-Encoding: chunked\r\n"
  19906. "\r\n"
  19907. "5\r\nhello\r\n";
  19908. with_single_response(short_chunked, [](Client &cli) {
  19909. auto handle = cli.open_stream("GET", "/");
  19910. ASSERT_TRUE(handle.is_valid());
  19911. read_all(handle);
  19912. EXPECT_TRUE(handle.has_read_error());
  19913. });
  19914. }
  19915. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19916. const char *responses[] = {
  19917. "HTTP/1.1 103 Early Hints\r\n"
  19918. "Link: </style.css>; rel=preload\r\n"
  19919. "\r\n"
  19920. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19921. "HTTP/1.1 100 Continue\r\n"
  19922. "X-Note: interim\r\n"
  19923. "\r\n"
  19924. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19925. };
  19926. for (auto response : responses) {
  19927. with_single_response(response, [](Client &cli) {
  19928. auto res = cli.Get("/");
  19929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19930. EXPECT_EQ(StatusCode::OK_200, res->status);
  19931. EXPECT_EQ("ok", res->body);
  19932. });
  19933. }
  19934. }
  19935. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19936. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19937. const std::string final_response =
  19938. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19939. std::string interims;
  19940. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19941. interims += interim;
  19942. }
  19943. with_single_response(interims + final_response, [](Client &cli) {
  19944. auto res = cli.Get("/");
  19945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19946. EXPECT_EQ("ok", res->body);
  19947. });
  19948. with_single_response(interims + interim + final_response, [](Client &cli) {
  19949. auto res = cli.Get("/");
  19950. ASSERT_FALSE(res);
  19951. EXPECT_EQ(Error::Read, res.error());
  19952. });
  19953. }
  19954. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19955. #ifndef _WIN32
  19956. signal(SIGPIPE, SIG_IGN);
  19957. #endif
  19958. // The server answers the head without asking for the body. Bytes it then
  19959. // reads on the connection would be taken for the body the request declared.
  19960. auto closed_by_client = false;
  19961. std::promise<int> port_promise;
  19962. auto server_thread = serve_single_response(
  19963. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19964. [&](socket_t sock) {
  19965. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19966. char buf[256];
  19967. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19968. });
  19969. Client cli("127.0.0.1", port_promise.get_future().get());
  19970. cli.set_keep_alive(true);
  19971. cli.set_read_timeout(1, 0);
  19972. // Long enough for the client to send Expect: 100-continue.
  19973. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19975. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19976. cli.Get("/second");
  19977. server_thread.join();
  19978. EXPECT_TRUE(closed_by_client);
  19979. }
  19980. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19981. // Long enough for the client to send Expect: 100-continue
  19982. with_single_response(
  19983. "HTTP/1.1 103 Early Hints\r\n"
  19984. "Link: </style.css>; rel=preload\r\n"
  19985. "\r\n"
  19986. "HTTP/1.1 401 Unauthorized\r\n"
  19987. "Content-Length: 0\r\n\r\n",
  19988. [](Client &cli) {
  19989. cli.set_read_timeout(2, 0);
  19990. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19992. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19993. });
  19994. }
  19995. #ifdef CPPHTTPLIB_SSL_ENABLED
  19996. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19997. #ifndef _WIN32
  19998. signal(SIGPIPE, SIG_IGN);
  19999. #endif
  20000. auto reused = false;
  20001. std::promise<int> port_promise;
  20002. auto server_thread = serve_single_response(
  20003. port_promise,
  20004. "HTTP/1.1 401 Unauthorized\r\n"
  20005. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20006. "Content-Length: 0\r\n\r\n",
  20007. [&](socket_t sock) {
  20008. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20009. char buf[256];
  20010. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20011. });
  20012. Client cli("127.0.0.1", port_promise.get_future().get());
  20013. cli.set_keep_alive(true);
  20014. cli.set_digest_auth("user", "pass");
  20015. cli.set_read_timeout(1, 0);
  20016. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20017. server_thread.join();
  20018. EXPECT_FALSE(reused);
  20019. }
  20020. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20021. // Any other answer to CONNECT would read as the origin's response.
  20022. struct {
  20023. const char *response;
  20024. bool passed_on;
  20025. } cases[] = {
  20026. {"HTTP/1.1 201 Created\r\n"
  20027. "Set-Cookie: session=from-proxy\r\n"
  20028. "Content-Length: 0\r\n\r\n",
  20029. false},
  20030. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20031. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20032. "Content-Length: 0\r\n\r\n",
  20033. true},
  20034. };
  20035. for (const auto &c : cases) {
  20036. std::promise<int> port_promise;
  20037. auto server_thread = serve_single_response(port_promise, c.response);
  20038. SSLClient cli("example.com", 443);
  20039. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20040. auto res = cli.Get("/");
  20041. server_thread.join();
  20042. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20043. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20044. if (res) {
  20045. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20046. }
  20047. }
  20048. }
  20049. #endif
  20050. // Records the client's error logger calls as "error METHOD path", or
  20051. // "error null" for a call without a request
  20052. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20053. return [&log](const Error &err, const Request *req) {
  20054. log.push_back(to_string(err) + " " +
  20055. (req ? req->method + " " + req->path : "null"));
  20056. };
  20057. }
  20058. // A failed request is reported once, with the request the caller made
  20059. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20060. Server svr;
  20061. svr.Get("/big", [](const Request &, Response &res) {
  20062. res.set_content(std::string(100000, 'b'), "text/plain");
  20063. });
  20064. auto port = svr.bind_to_any_port(HOST);
  20065. std::thread t([&]() { svr.listen_after_bind(); });
  20066. auto se = detail::scope_exit([&] {
  20067. svr.stop();
  20068. t.join();
  20069. });
  20070. svr.wait_until_ready();
  20071. Client cli(HOST, port);
  20072. std::vector<std::string> log;
  20073. cli.set_error_logger(record_errors(log));
  20074. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20075. cli.Get("/big", [](const char *, size_t) { return false; });
  20076. EXPECT_EQ(expected, log);
  20077. log.clear();
  20078. cli.Get("/big", [](size_t, size_t) { return false; });
  20079. EXPECT_EQ(expected, log);
  20080. }
  20081. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20082. // Fails while the body is read
  20083. auto broken = [](const Request &, Response &res) {
  20084. res.set_content_provider(10, "text/plain",
  20085. [](size_t, size_t, DataSink &) { return false; });
  20086. };
  20087. Server other;
  20088. other.Get("/broken", broken);
  20089. auto other_port = other.bind_to_any_port(HOST);
  20090. std::thread other_t([&]() { other.listen_after_bind(); });
  20091. auto other_se = detail::scope_exit([&] {
  20092. other.stop();
  20093. other_t.join();
  20094. });
  20095. other.wait_until_ready();
  20096. Server svr;
  20097. svr.Get("/broken", broken);
  20098. svr.Get("/same-origin",
  20099. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20100. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20101. res.set_redirect("http://" + std::string(HOST) + ":" +
  20102. std::to_string(other_port) + "/broken");
  20103. });
  20104. auto port = svr.bind_to_any_port(HOST);
  20105. std::thread t([&]() { svr.listen_after_bind(); });
  20106. auto se = detail::scope_exit([&] {
  20107. svr.stop();
  20108. t.join();
  20109. });
  20110. svr.wait_until_ready();
  20111. Client cli(HOST, port);
  20112. cli.set_follow_location(true);
  20113. std::vector<std::string> log;
  20114. cli.set_error_logger(record_errors(log));
  20115. for (auto path : {"/same-origin", "/cross-origin"}) {
  20116. log.clear();
  20117. auto res = cli.Get(path);
  20118. ASSERT_FALSE(res);
  20119. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20120. log);
  20121. }
  20122. }
  20123. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20124. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20125. std::vector<std::string> log;
  20126. cli.set_error_logger(record_errors(log));
  20127. auto handle = cli.open_stream("GET", "/x");
  20128. EXPECT_FALSE(handle.is_valid());
  20129. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20130. log);
  20131. });
  20132. }
  20133. #ifdef CPPHTTPLIB_SSL_ENABLED
  20134. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20135. // Not a TLS server, so the handshake fails. It waits for a request line in
  20136. // the handshake bytes, so a short read timeout lets it close quickly.
  20137. Server svr;
  20138. svr.set_read_timeout(0, 100000);
  20139. svr.Get("/x", [](const Request &, Response &res) {
  20140. res.set_content("x", "text/plain");
  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. std::vector<std::string> log;
  20150. SSLClient cli(HOST, port);
  20151. cli.enable_server_certificate_verification(false);
  20152. cli.set_error_logger(record_errors(log));
  20153. auto res = cli.Get("/x");
  20154. ASSERT_FALSE(res);
  20155. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20156. log.clear();
  20157. auto handle = cli.open_stream("GET", "/x");
  20158. EXPECT_FALSE(handle.is_valid());
  20159. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20160. log.clear();
  20161. SSLClient no_ca(HOST, port);
  20162. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20163. no_ca.set_error_logger(record_errors(log));
  20164. res = no_ca.Get("/x");
  20165. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20166. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20167. }
  20168. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20169. #ifndef _WIN32
  20170. signal(SIGPIPE, SIG_IGN);
  20171. #endif
  20172. // Refused, answered with a challenge, or closed without an answer
  20173. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20174. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20175. "Content-Length: 0\r\n\r\n",
  20176. ""}) {
  20177. std::promise<int> port_promise;
  20178. auto server_thread = serve_single_response(port_promise, response);
  20179. SSLClient cli("example.com", 443);
  20180. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20181. std::vector<std::string> log;
  20182. cli.set_error_logger(record_errors(log));
  20183. auto res = cli.Get("/");
  20184. server_thread.join();
  20185. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20186. << response;
  20187. }
  20188. }
  20189. #endif
  20190. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20191. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20192. // the chunked coding and drop Content-Length, so a front-end that trusts
  20193. // Content-Length would disagree about where the body ends (response
  20194. // smuggling). The client must reject such a response.
  20195. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20196. for (const char *te : {"chunked", "gzip, chunked"}) {
  20197. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20198. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20199. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20200. "5\r\nhello\r\n0\r\n\r\n";
  20201. with_single_response(response, [&](Client &cli) {
  20202. auto res = cli.Get("/");
  20203. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20204. EXPECT_EQ(Error::Read, res.error()) << te;
  20205. });
  20206. with_single_response(response, [&](Client &cli) {
  20207. auto handle = cli.open_stream("GET", "/");
  20208. EXPECT_FALSE(handle.is_valid()) << te;
  20209. EXPECT_EQ(Error::Read, handle.error) << te;
  20210. });
  20211. }
  20212. }
  20213. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20214. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20215. // closing the connection (unlike a request, which must be rejected).
  20216. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20217. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20218. "Transfer-Encoding: chunked\r\n"
  20219. "Connection: close\r\n"
  20220. "\r\n"
  20221. "5\r\nhello\r\n0\r\n\r\n",
  20222. "HTTP/1.1 200 OK\r\n"
  20223. "Transfer-Encoding: gzip\r\n"
  20224. "Connection: close\r\n"
  20225. "\r\n"
  20226. "hello"}) {
  20227. with_single_response(response, [&](Client &cli) {
  20228. auto res = cli.Get("/");
  20229. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20230. EXPECT_EQ("hello", res->body);
  20231. });
  20232. with_single_response(response, [&](Client &cli) {
  20233. auto handle = cli.open_stream("GET", "/");
  20234. ASSERT_TRUE(handle.is_valid()) << response;
  20235. EXPECT_EQ("hello", read_all(handle));
  20236. });
  20237. }
  20238. }
  20239. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20240. // framing headers describe nothing to read and must not be rejected.
  20241. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20242. const std::string framing = "Content-Length: 5\r\n"
  20243. "Transfer-Encoding: chunked\r\n"
  20244. "Connection: close\r\n"
  20245. "\r\n";
  20246. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20247. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20248. });
  20249. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20250. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20251. });
  20252. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20253. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20254. with_single_response(response, [&](Client &cli) {
  20255. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20256. });
  20257. with_single_response(response, [&](Client &cli) {
  20258. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20259. });
  20260. }
  20261. }
  20262. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20263. // header section, so a stream opened on one has nothing to read, whatever
  20264. // framing or coding headers it carries.
  20265. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20266. struct Case {
  20267. const char *method;
  20268. const char *status;
  20269. };
  20270. // A reader of the declared body reports an early close when nothing
  20271. // follows, and hands back what does.
  20272. struct Framing {
  20273. const char *headers;
  20274. const char *after;
  20275. };
  20276. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20277. Case{"GET", "304 Not Modified"}}) {
  20278. for (const auto &f :
  20279. {Framing{"Content-Length: 5\r\n", ""},
  20280. Framing{"Content-Length: 5\r\n", "hello"},
  20281. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20282. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20283. // Not decoded, so a build without Brotli opens it too
  20284. Framing{"Content-Encoding: br\r\n", ""}}) {
  20285. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20286. "Connection: close\r\n"
  20287. "\r\n" +
  20288. f.after;
  20289. with_single_response(response, [&](Client &cli) {
  20290. auto handle = cli.open_stream(c.method, "/");
  20291. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20292. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20293. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20294. });
  20295. }
  20296. }
  20297. }
  20298. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20299. // response, is faulty framing, so the connection is not reused after it.
  20300. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20301. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20302. "Content-Length: 0\r\n"
  20303. "Transfer-Encoding: chunked\r\n"
  20304. "\r\n"
  20305. "5\r\nhello\r\n0\r\n\r\n",
  20306. "HTTP/1.0 200 Connection established\r\n"
  20307. "Connection: keep-alive\r\n"
  20308. "Transfer-Encoding: chunked\r\n"
  20309. "\r\n"
  20310. "5\r\nhello\r\n0\r\n\r\n"}) {
  20311. with_single_response(response, [&](Client &cli) {
  20312. cli.set_keep_alive(true);
  20313. auto res = cli.Get("/");
  20314. ASSERT_TRUE(res) << response;
  20315. EXPECT_EQ("hello", res->body);
  20316. EXPECT_FALSE(cli.is_socket_open()) << response;
  20317. });
  20318. }
  20319. }
  20320. // A payload max length of 0 means no limit, however the body is framed.
  20321. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20322. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20323. "Transfer-Encoding: chunked\r\n"
  20324. "\r\n"
  20325. "5\r\nhello\r\n0\r\n\r\n",
  20326. "HTTP/1.1 200 OK\r\n"
  20327. "Connection: close\r\n"
  20328. "\r\n"
  20329. "hello"}) {
  20330. with_single_response(response, [&](Client &cli) {
  20331. cli.set_payload_max_length(0);
  20332. auto res = cli.Get("/");
  20333. ASSERT_TRUE(res) << response;
  20334. EXPECT_EQ("hello", res->body) << response;
  20335. });
  20336. }
  20337. }
  20338. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20339. Server svr;
  20340. svr.set_payload_max_length(0);
  20341. svr.Post("/echo", [](const Request &req, Response &res) {
  20342. res.set_content(req.body, "text/plain");
  20343. });
  20344. auto port = svr.bind_to_any_port(HOST);
  20345. thread t = thread([&] { svr.listen_after_bind(); });
  20346. auto se = detail::scope_exit([&] {
  20347. svr.stop();
  20348. t.join();
  20349. ASSERT_FALSE(svr.is_running());
  20350. });
  20351. svr.wait_until_ready();
  20352. Client cli(HOST, port);
  20353. auto res = cli.Post(
  20354. "/echo",
  20355. [](size_t /*offset*/, DataSink &sink) {
  20356. sink.write("hello", 5);
  20357. sink.done();
  20358. return true;
  20359. },
  20360. "text/plain");
  20361. ASSERT_TRUE(res);
  20362. EXPECT_EQ(StatusCode::OK_200, res->status);
  20363. EXPECT_EQ("hello", res->body);
  20364. }
  20365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20366. TEST_F(OpenStreamTest, Gzip) {
  20367. Client cli("127.0.0.1", port_);
  20368. auto handle = cli.open_stream("GET", "/compressible", {},
  20369. {{"Accept-Encoding", "gzip"}});
  20370. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20371. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20372. }
  20373. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20374. Client cli("127.0.0.1", port_);
  20375. auto handle =
  20376. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20377. {{"Accept-Encoding", "gzip"}});
  20378. ASSERT_TRUE(handle.is_valid());
  20379. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20380. EXPECT_EQ("123456789", read_all(handle));
  20381. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20382. }
  20383. #endif
  20384. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20385. TEST_F(OpenStreamTest, Brotli) {
  20386. Client cli("127.0.0.1", port_);
  20387. auto handle =
  20388. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20389. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20390. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20391. }
  20392. #endif
  20393. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20394. TEST_F(OpenStreamTest, Zstd) {
  20395. Client cli("127.0.0.1", port_);
  20396. auto handle = cli.open_stream("GET", "/compressible", {},
  20397. {{"Accept-Encoding", "zstd"}});
  20398. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20399. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20400. }
  20401. #endif
  20402. #ifdef CPPHTTPLIB_SSL_ENABLED
  20403. class SSLOpenStreamTest : public ::testing::Test {
  20404. protected:
  20405. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20406. void SetUp() override {
  20407. svr_.Get("/hello", [](const Request &, Response &res) {
  20408. res.set_content("Hello SSL World!", "text/plain");
  20409. });
  20410. svr_.Get("/chunked", [](const Request &, Response &res) {
  20411. res.set_chunked_content_provider("text/plain",
  20412. [](size_t offset, DataSink &sink) {
  20413. if (offset < 15) {
  20414. sink.write("chunk", 5);
  20415. return true;
  20416. }
  20417. sink.done();
  20418. return true;
  20419. });
  20420. });
  20421. svr_.Post("/echo", [](const Request &req, Response &res) {
  20422. res.set_content(req.body, req.get_header_value("Content-Type"));
  20423. });
  20424. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20425. std::string body = req.body;
  20426. res.set_chunked_content_provider(
  20427. "text/plain", [body](size_t offset, DataSink &sink) {
  20428. if (offset < body.size()) {
  20429. sink.write(body.data() + offset, body.size() - offset);
  20430. }
  20431. sink.done();
  20432. return true;
  20433. });
  20434. });
  20435. port_ = svr_.bind_to_any_port("127.0.0.1");
  20436. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20437. svr_.wait_until_ready();
  20438. }
  20439. void TearDown() override {
  20440. svr_.stop();
  20441. if (thread_.joinable()) thread_.join();
  20442. }
  20443. SSLServer svr_;
  20444. std::thread thread_;
  20445. int port_ = 0;
  20446. };
  20447. TEST_F(SSLOpenStreamTest, Basic) {
  20448. SSLClient cli("127.0.0.1", port_);
  20449. cli.enable_server_certificate_verification(false);
  20450. auto handle = cli.open_stream("GET", "/hello");
  20451. ASSERT_TRUE(handle.is_valid());
  20452. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20453. }
  20454. TEST_F(SSLOpenStreamTest, Chunked) {
  20455. SSLClient cli("127.0.0.1", port_);
  20456. cli.enable_server_certificate_verification(false);
  20457. auto handle = cli.open_stream("GET", "/chunked");
  20458. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20459. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20460. "Transfer-Encoding") == "chunked");
  20461. auto body = read_all(handle);
  20462. EXPECT_EQ("chunkchunkchunk", body);
  20463. }
  20464. TEST_F(SSLOpenStreamTest, Post) {
  20465. SSLClient cli("127.0.0.1", port_);
  20466. cli.enable_server_certificate_verification(false);
  20467. auto handle =
  20468. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20469. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20470. EXPECT_EQ(200, handle.response->status);
  20471. auto body = read_all(handle);
  20472. EXPECT_EQ("Hello SSL POST", body);
  20473. }
  20474. TEST_F(SSLOpenStreamTest, PostChunked) {
  20475. SSLClient cli("127.0.0.1", port_);
  20476. cli.enable_server_certificate_verification(false);
  20477. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20478. "Chunked SSL Data", "text/plain");
  20479. ASSERT_TRUE(handle.is_valid());
  20480. EXPECT_EQ(200, handle.response->status);
  20481. auto body = read_all(handle);
  20482. EXPECT_EQ("Chunked SSL Data", body);
  20483. }
  20484. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20485. // Content-Length is terminated by the server closing the connection. When the
  20486. // SSL peer sends a close_notify after the body, the client must treat it as a
  20487. // clean EOF and return a successful response rather than an error.
  20488. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20490. ASSERT_TRUE(svr.is_valid());
  20491. svr.set_keep_alive_max_count(1);
  20492. const std::string expected_body = "Hello from connection-close response!";
  20493. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20494. res.set_content_provider("text/plain",
  20495. [&](size_t offset, DataSink &sink) -> bool {
  20496. if (offset < expected_body.size()) {
  20497. sink.write(expected_body.data() + offset,
  20498. expected_body.size() - offset);
  20499. }
  20500. sink.done();
  20501. return true;
  20502. });
  20503. });
  20504. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20505. auto se = detail::scope_exit([&] {
  20506. svr.stop();
  20507. listen_thread.join();
  20508. ASSERT_FALSE(svr.is_running());
  20509. });
  20510. svr.wait_until_ready();
  20511. SSLClient cli(HOST, PORT);
  20512. cli.enable_server_certificate_verification(false);
  20513. auto res = cli.Get("/no-content-length");
  20514. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20515. EXPECT_EQ(StatusCode::OK_200, res->status);
  20516. EXPECT_EQ(expected_body, res->body);
  20517. }
  20518. #endif // CPPHTTPLIB_SSL_ENABLED
  20519. //==============================================================================
  20520. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20521. // results for various scenarios.
  20522. //==============================================================================
  20523. TEST(ParityTest, GetVsOpenStream) {
  20524. Server svr;
  20525. const std::string path = "/parity";
  20526. const std::string content = "Parity test content: hello world";
  20527. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20528. res.set_content(content, "text/plain");
  20529. });
  20530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20531. auto se = detail::scope_exit([&] {
  20532. svr.stop();
  20533. t.join();
  20534. ASSERT_FALSE(svr.is_running());
  20535. });
  20536. svr.wait_until_ready();
  20537. Client cli(HOST, PORT);
  20538. // Non-stream path
  20539. auto r1 = cli.Get(path);
  20540. ASSERT_TRUE(r1);
  20541. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20542. // Stream path
  20543. auto h = cli.open_stream("GET", path);
  20544. ASSERT_TRUE(h.is_valid());
  20545. EXPECT_EQ(r1->body, read_all(h));
  20546. }
  20547. // Helper to compress data with provided compressor type T
  20548. template <typename Compressor>
  20549. static std::string compress_payload_for_parity(const std::string &in) {
  20550. std::string out;
  20551. Compressor compressor;
  20552. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20553. [&](const char *data, size_t n) {
  20554. out.append(data, n);
  20555. return true;
  20556. });
  20557. EXPECT_TRUE(ok);
  20558. return out;
  20559. }
  20560. // Helper function for compression parity tests
  20561. template <typename Compressor>
  20562. static void test_compression_parity(const std::string &original,
  20563. const std::string &path,
  20564. const std::string &encoding) {
  20565. const std::string compressed =
  20566. compress_payload_for_parity<Compressor>(original);
  20567. Server svr;
  20568. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20569. res.set_content(compressed, "application/octet-stream");
  20570. res.set_header("Content-Encoding", encoding);
  20571. });
  20572. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20573. auto se = detail::scope_exit([&] {
  20574. svr.stop();
  20575. t.join();
  20576. ASSERT_FALSE(svr.is_running());
  20577. });
  20578. svr.wait_until_ready();
  20579. Client cli(HOST, PORT);
  20580. // Non-streaming
  20581. {
  20582. auto res = cli.Get(path);
  20583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20584. EXPECT_EQ(StatusCode::OK_200, res->status);
  20585. EXPECT_EQ(original, res->body);
  20586. }
  20587. // Streaming
  20588. {
  20589. auto h = cli.open_stream("GET", path);
  20590. ASSERT_TRUE(h.is_valid());
  20591. EXPECT_EQ(original, read_all(h));
  20592. }
  20593. }
  20594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20595. TEST(ParityTest, Gzip) {
  20596. test_compression_parity<detail::gzip_compressor>(
  20597. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20598. }
  20599. #endif
  20600. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20601. TEST(ParityTest, Brotli) {
  20602. test_compression_parity<detail::brotli_compressor>(
  20603. "Hello, brotli parity test payload", "/parity-br", "br");
  20604. }
  20605. #endif
  20606. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20607. TEST(ParityTest, Zstd) {
  20608. test_compression_parity<detail::zstd_compressor>(
  20609. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20610. }
  20611. #endif
  20612. //==============================================================================
  20613. // New Stream API Tests
  20614. //==============================================================================
  20615. inline std::string read_body(httplib::stream::Result &result) {
  20616. std::string body;
  20617. while (result.next()) {
  20618. body.append(result.data(), result.size());
  20619. }
  20620. return body;
  20621. }
  20622. TEST(ClientConnectionTest, Basic) {
  20623. httplib::ClientConnection conn;
  20624. EXPECT_FALSE(conn.is_open());
  20625. conn.sock = 1;
  20626. EXPECT_TRUE(conn.is_open());
  20627. httplib::ClientConnection conn2(std::move(conn));
  20628. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20629. conn2.sock = INVALID_SOCKET;
  20630. }
  20631. // Unified test server for all stream::* tests
  20632. class StreamApiTest : public ::testing::Test {
  20633. protected:
  20634. void SetUp() override {
  20635. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20636. res.set_content("Hello World!", "text/plain");
  20637. });
  20638. svr_.Get("/echo-params",
  20639. [](const httplib::Request &req, httplib::Response &res) {
  20640. std::string r;
  20641. for (const auto &p : req.params) {
  20642. if (!r.empty()) r += "&";
  20643. r += p.first + "=" + p.second;
  20644. }
  20645. res.set_content(r, "text/plain");
  20646. });
  20647. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20648. res.set_content(req.body, req.get_header_value("Content-Type"));
  20649. });
  20650. svr_.Post("/echo-headers",
  20651. [](const httplib::Request &req, httplib::Response &res) {
  20652. std::string r;
  20653. for (const auto &h : req.headers)
  20654. r += h.first + ": " + h.second + "\n";
  20655. res.set_content(r, "text/plain");
  20656. });
  20657. svr_.Post("/echo-params",
  20658. [](const httplib::Request &req, httplib::Response &res) {
  20659. std::string r = "params:";
  20660. for (const auto &p : req.params)
  20661. r += p.first + "=" + p.second + ";";
  20662. res.set_content(r + " body:" + req.body, "text/plain");
  20663. });
  20664. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20665. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20666. });
  20667. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20668. res.set_content("PUT:" + req.body, "text/plain");
  20669. });
  20670. svr_.Patch("/echo",
  20671. [](const httplib::Request &req, httplib::Response &res) {
  20672. res.set_content("PATCH:" + req.body, "text/plain");
  20673. });
  20674. svr_.Delete(
  20675. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20676. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20677. "text/plain");
  20678. });
  20679. svr_.Get("/head-test",
  20680. [](const httplib::Request &, httplib::Response &res) {
  20681. res.set_content("body for HEAD", "text/plain");
  20682. });
  20683. svr_.Options("/options",
  20684. [](const httplib::Request &, httplib::Response &res) {
  20685. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20686. });
  20687. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20688. svr_.wait_until_ready();
  20689. }
  20690. void TearDown() override {
  20691. svr_.stop();
  20692. if (thread_.joinable()) thread_.join();
  20693. }
  20694. httplib::Server svr_;
  20695. std::thread thread_;
  20696. };
  20697. // stream::Get tests
  20698. TEST_F(StreamApiTest, GetBasic) {
  20699. httplib::Client cli(HOST, PORT);
  20700. auto result = httplib::stream::Get(cli, "/hello");
  20701. ASSERT_TRUE(result.is_valid());
  20702. EXPECT_EQ(200, result.status());
  20703. EXPECT_EQ("Hello World!", read_body(result));
  20704. }
  20705. TEST_F(StreamApiTest, GetWithParams) {
  20706. httplib::Client cli(HOST, PORT);
  20707. httplib::Params params{{"foo", "bar"}};
  20708. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20709. ASSERT_TRUE(result.is_valid());
  20710. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20711. }
  20712. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20713. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20714. httplib::Client cli(HOST, PORT);
  20715. cli.set_payload_max_length(0);
  20716. auto result = httplib::stream::Get(cli, "/hello");
  20717. ASSERT_TRUE(result.is_valid());
  20718. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20719. EXPECT_EQ("Hello World!", read_body(result));
  20720. }
  20721. #endif
  20722. TEST_F(StreamApiTest, GetConnectionError) {
  20723. httplib::Client cli(HOST, 9999);
  20724. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20725. }
  20726. TEST_F(StreamApiTest, Get404) {
  20727. httplib::Client cli(HOST, PORT);
  20728. auto result = httplib::stream::Get(cli, "/nonexistent");
  20729. EXPECT_TRUE(result.is_valid());
  20730. EXPECT_EQ(404, result.status());
  20731. }
  20732. // stream::Post tests
  20733. TEST_F(StreamApiTest, PostBasic) {
  20734. httplib::Client cli(HOST, PORT);
  20735. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20736. "application/json");
  20737. ASSERT_TRUE(result.is_valid());
  20738. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20739. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20740. }
  20741. TEST_F(StreamApiTest, PostWithHeaders) {
  20742. httplib::Client cli(HOST, PORT);
  20743. httplib::Headers headers{{"X-Custom", "value"}};
  20744. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20745. "text/plain");
  20746. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20747. }
  20748. TEST_F(StreamApiTest, PostWithParams) {
  20749. httplib::Client cli(HOST, PORT);
  20750. httplib::Params params{{"k", "v"}};
  20751. auto result =
  20752. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20753. auto body = read_body(result);
  20754. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20755. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20756. }
  20757. TEST_F(StreamApiTest, PostLarge) {
  20758. httplib::Client cli(HOST, PORT);
  20759. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20760. size_t total = 0;
  20761. while (result.next()) {
  20762. total += result.size();
  20763. }
  20764. EXPECT_EQ(100u * 1024u, total);
  20765. }
  20766. // stream::Put/Patch tests
  20767. TEST_F(StreamApiTest, PutAndPatch) {
  20768. httplib::Client cli(HOST, PORT);
  20769. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20770. EXPECT_EQ("PUT:test", read_body(put));
  20771. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20772. EXPECT_EQ("PATCH:test", read_body(patch));
  20773. }
  20774. // stream::Delete tests
  20775. TEST_F(StreamApiTest, Delete) {
  20776. httplib::Client cli(HOST, PORT);
  20777. auto del1 = httplib::stream::Delete(cli, "/resource");
  20778. EXPECT_EQ("Deleted", read_body(del1));
  20779. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20780. EXPECT_EQ("Deleted:data", read_body(del2));
  20781. }
  20782. // stream::Head/Options tests
  20783. TEST_F(StreamApiTest, HeadAndOptions) {
  20784. httplib::Client cli(HOST, PORT);
  20785. auto head = httplib::stream::Head(cli, "/head-test");
  20786. EXPECT_TRUE(head.is_valid());
  20787. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20788. auto opts = httplib::stream::Options(cli, "/options");
  20789. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20790. }
  20791. // SSL stream::* tests
  20792. #ifdef CPPHTTPLIB_SSL_ENABLED
  20793. class SSLStreamApiTest : public ::testing::Test {
  20794. protected:
  20795. void SetUp() override {
  20796. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20797. res.set_content("Hello SSL!", "text/plain");
  20798. });
  20799. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20800. res.set_content(req.body, "text/plain");
  20801. });
  20802. port_ = svr_.bind_to_any_port("127.0.0.1");
  20803. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20804. svr_.wait_until_ready();
  20805. }
  20806. void TearDown() override {
  20807. svr_.stop();
  20808. if (thread_.joinable()) thread_.join();
  20809. }
  20810. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20811. std::thread thread_;
  20812. int port_ = 0;
  20813. };
  20814. TEST_F(SSLStreamApiTest, GetAndPost) {
  20815. httplib::SSLClient cli("127.0.0.1", port_);
  20816. cli.enable_server_certificate_verification(false);
  20817. auto get = httplib::stream::Get(cli, "/hello");
  20818. EXPECT_EQ("Hello SSL!", read_body(get));
  20819. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20820. EXPECT_EQ("test", read_body(post));
  20821. }
  20822. #endif
  20823. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20824. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20825. // BodyReader
  20826. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20827. // Test that read timeout during streaming is detected
  20828. // Use a large content-length response where server delays mid-stream
  20829. Server svr;
  20830. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20831. // Send a large response with delay in the middle
  20832. res.set_content_provider(
  20833. 1000, // content_length
  20834. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20835. if (offset < 100) {
  20836. // Send first 100 bytes immediately
  20837. std::string data(100, 'A');
  20838. sink.write(data.c_str(), data.size());
  20839. return true;
  20840. }
  20841. // Then delay longer than client timeout
  20842. std::this_thread::sleep_for(std::chrono::seconds(3));
  20843. std::string data(900, 'B');
  20844. sink.write(data.c_str(), data.size());
  20845. return true;
  20846. });
  20847. });
  20848. auto port = 8091;
  20849. std::thread t([&]() { svr.listen("localhost", port); });
  20850. svr.wait_until_ready();
  20851. Client cli("localhost", port);
  20852. cli.set_read_timeout(1, 0); // 1 second timeout
  20853. auto handle = cli.open_stream("GET", "/slow-stream");
  20854. ASSERT_TRUE(handle.is_valid());
  20855. char buf[256];
  20856. ssize_t total = 0;
  20857. ssize_t n;
  20858. bool got_error = false;
  20859. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20860. total += n;
  20861. }
  20862. if (n < 0) {
  20863. got_error = true;
  20864. // Should be timeout or read error
  20865. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20866. handle.get_read_error() == Error::Read)
  20867. << "Actual error: " << to_string(handle.get_read_error());
  20868. }
  20869. // Either we got an error, or we got less data than expected
  20870. EXPECT_TRUE(got_error || total < 1000)
  20871. << "Expected timeout but got all " << total << " bytes";
  20872. svr.stop();
  20873. t.join();
  20874. }
  20875. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20876. // Test connection closed detection via BodyReader
  20877. Server svr;
  20878. std::atomic<bool> close_now{false};
  20879. svr.Get("/will-close", [&](const Request &, Response &res) {
  20880. res.set_content_provider(
  20881. 10000, // Large content_length that we won't fully send
  20882. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20883. if (offset < 100) {
  20884. std::string data(100, 'X');
  20885. sink.write(data.c_str(), data.size());
  20886. return true;
  20887. }
  20888. // Wait for signal then abort
  20889. while (!close_now) {
  20890. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20891. }
  20892. return false; // Abort - server will close connection
  20893. });
  20894. });
  20895. auto port = 8092;
  20896. std::thread t([&]() { svr.listen("localhost", port); });
  20897. svr.wait_until_ready();
  20898. Client cli("localhost", port);
  20899. auto handle = cli.open_stream("GET", "/will-close");
  20900. ASSERT_TRUE(handle.is_valid());
  20901. char buf[256];
  20902. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20903. EXPECT_GT(n, 0) << "First read should succeed";
  20904. // Signal server to close
  20905. close_now = true;
  20906. // Keep reading until error or EOF
  20907. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20908. // Keep reading
  20909. }
  20910. // Should get an error since content_length wasn't satisfied
  20911. if (n < 0) {
  20912. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20913. handle.get_read_error() == Error::Read)
  20914. << "Actual error: " << to_string(handle.get_read_error());
  20915. }
  20916. svr.stop();
  20917. t.join();
  20918. }
  20919. #ifdef CPPHTTPLIB_SSL_ENABLED
  20920. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20921. // Test that read timeout during SSL streaming is detected
  20922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20923. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20924. res.set_content_provider(
  20925. 1000, "text/plain",
  20926. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20927. if (offset < 100) {
  20928. std::string data(100, 'A');
  20929. sink.write(data.c_str(), data.size());
  20930. return true;
  20931. }
  20932. std::this_thread::sleep_for(std::chrono::seconds(3));
  20933. std::string data(900, 'B');
  20934. sink.write(data.c_str(), data.size());
  20935. return true;
  20936. });
  20937. });
  20938. auto port = 8093;
  20939. std::thread t([&]() { svr.listen("localhost", port); });
  20940. svr.wait_until_ready();
  20941. SSLClient cli("localhost", port);
  20942. cli.enable_server_certificate_verification(false);
  20943. cli.set_read_timeout(1, 0); // 1 second timeout
  20944. auto handle = cli.open_stream("GET", "/slow-stream");
  20945. ASSERT_TRUE(handle.is_valid());
  20946. char buf[256];
  20947. ssize_t total = 0;
  20948. ssize_t n;
  20949. bool got_error = false;
  20950. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20951. total += n;
  20952. }
  20953. if (n < 0) {
  20954. got_error = true;
  20955. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20956. handle.get_read_error() == Error::Read)
  20957. << "Actual error: " << to_string(handle.get_read_error());
  20958. }
  20959. EXPECT_TRUE(got_error || total < 1000)
  20960. << "Expected timeout but got all " << total << " bytes";
  20961. svr.stop();
  20962. t.join();
  20963. }
  20964. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20965. // Test SSL connection closed detection
  20966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20967. std::atomic<bool> close_now{false};
  20968. svr.Get("/will-close", [&](const Request &, Response &res) {
  20969. res.set_content_provider(
  20970. 10000, "text/plain",
  20971. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20972. if (offset < 100) {
  20973. std::string data(100, 'X');
  20974. sink.write(data.c_str(), data.size());
  20975. return true;
  20976. }
  20977. while (!close_now) {
  20978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20979. }
  20980. return false;
  20981. });
  20982. });
  20983. auto port = 8094;
  20984. std::thread t([&]() { svr.listen("localhost", port); });
  20985. svr.wait_until_ready();
  20986. SSLClient cli("localhost", port);
  20987. cli.enable_server_certificate_verification(false);
  20988. auto handle = cli.open_stream("GET", "/will-close");
  20989. ASSERT_TRUE(handle.is_valid());
  20990. char buf[256];
  20991. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20992. EXPECT_GT(n, 0);
  20993. // Signal server to close
  20994. close_now = true;
  20995. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20996. // Keep reading
  20997. }
  20998. if (n < 0) {
  20999. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21000. handle.get_read_error() == Error::Read)
  21001. << "Actual error: " << to_string(handle.get_read_error());
  21002. }
  21003. svr.stop();
  21004. t.join();
  21005. }
  21006. #endif
  21007. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21008. using namespace httplib;
  21009. // Create a test file
  21010. const char *fname = "etag_testfile.txt";
  21011. const char *content = "etag-content";
  21012. {
  21013. std::ofstream ofs(fname);
  21014. ofs << content;
  21015. ASSERT_TRUE(ofs.good());
  21016. }
  21017. Server svr;
  21018. svr.set_mount_point("/static", ".");
  21019. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21020. svr.wait_until_ready();
  21021. Client cli(HOST, PORT);
  21022. // First request: should get 200 with ETag header
  21023. auto res1 = cli.Get("/static/etag_testfile.txt");
  21024. ASSERT_TRUE(res1);
  21025. ASSERT_EQ(200, res1->status);
  21026. ASSERT_TRUE(res1->has_header("ETag"));
  21027. std::string etag = res1->get_header_value("ETag");
  21028. EXPECT_FALSE(etag.empty());
  21029. // Verify ETag format: W/"hex-hex"
  21030. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21031. EXPECT_EQ('W', etag[0]);
  21032. EXPECT_EQ('/', etag[1]);
  21033. EXPECT_EQ('"', etag[2]);
  21034. EXPECT_EQ('"', etag.back());
  21035. // Exact match: expect 304 Not Modified
  21036. Headers h2 = {{"If-None-Match", etag}};
  21037. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21038. ASSERT_TRUE(res2);
  21039. EXPECT_EQ(304, res2->status);
  21040. // Wildcard match: expect 304 Not Modified
  21041. Headers h3 = {{"If-None-Match", "*"}};
  21042. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21043. ASSERT_TRUE(res3);
  21044. EXPECT_EQ(304, res3->status);
  21045. // Non-matching ETag: expect 200
  21046. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21047. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21048. ASSERT_TRUE(res4);
  21049. EXPECT_EQ(200, res4->status);
  21050. // Multiple ETags with one matching: expect 304
  21051. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21052. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21053. ASSERT_TRUE(res5);
  21054. EXPECT_EQ(304, res5->status);
  21055. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21056. // that equivalent to the single comma-separated list above, so the match on
  21057. // the second line must still be found.
  21058. Headers h6;
  21059. h6.emplace("If-None-Match", "W/\"other\"");
  21060. h6.emplace("If-None-Match", etag);
  21061. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21062. ASSERT_TRUE(res6);
  21063. EXPECT_EQ(304, res6->status);
  21064. svr.stop();
  21065. t.join();
  21066. std::remove(fname);
  21067. }
  21068. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21069. using namespace httplib;
  21070. Server svr;
  21071. svr.set_mount_point("/static", ".");
  21072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21073. svr.wait_until_ready();
  21074. Client cli(HOST, PORT);
  21075. // Send If-None-Match: * to a non-existent file
  21076. Headers h = {{"If-None-Match", "*"}};
  21077. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21079. EXPECT_EQ(404, res->status);
  21080. svr.stop();
  21081. t.join();
  21082. }
  21083. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21084. using namespace httplib;
  21085. // Create a test file
  21086. const char *fname = "etag_boundary_testfile.txt";
  21087. const char *content = "boundary-test";
  21088. {
  21089. std::ofstream ofs(fname);
  21090. ofs << content;
  21091. ASSERT_TRUE(ofs.good());
  21092. }
  21093. Server svr;
  21094. svr.set_mount_point("/static", ".");
  21095. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21096. svr.wait_until_ready();
  21097. Client cli(HOST, PORT);
  21098. // Get the actual ETag
  21099. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21100. ASSERT_TRUE(res1);
  21101. ASSERT_EQ(200, res1->status);
  21102. ASSERT_TRUE(res1->has_header("ETag"));
  21103. std::string etag = res1->get_header_value("ETag");
  21104. // Test 1: Very long ETag value (longer than actual ETag)
  21105. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21106. Headers h1 = {{"If-None-Match", "W/"
  21107. "\"very-long-etag-value-that-is-much-longer-"
  21108. "than-the-actual-etag-value\""}};
  21109. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21110. ASSERT_TRUE(res2);
  21111. EXPECT_EQ(200, res2->status); // Should not match
  21112. // Test 2: Long string followed by wildcard
  21113. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21114. // string)
  21115. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21116. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21117. ASSERT_TRUE(res3);
  21118. EXPECT_EQ(304, res3->status); // Should match on "*"
  21119. // Test 3: Wildcard followed by long string
  21120. // Should match on "*" immediately and return 304
  21121. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21122. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21123. ASSERT_TRUE(res4);
  21124. EXPECT_EQ(304, res4->status); // Should match on "*"
  21125. // Test 4: Multiple long non-matching values
  21126. // Should NOT match and return 200 (test that all comparisons are safe)
  21127. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21128. "W/\"second-long-non-matching-value\", "
  21129. "W/\"third-long-non-matching-value\""}};
  21130. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21131. ASSERT_TRUE(res5);
  21132. EXPECT_EQ(200, res5->status); // Should not match
  21133. // Test 5: Single character that is not "*" (edge case)
  21134. Headers h5 = {{"If-None-Match", "X"}};
  21135. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21136. ASSERT_TRUE(res6);
  21137. EXPECT_EQ(200, res6->status); // Should not match
  21138. svr.stop();
  21139. t.join();
  21140. std::remove(fname);
  21141. }
  21142. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21143. using namespace httplib;
  21144. // Create a test file
  21145. const char *fname = "ims_testfile.txt";
  21146. const char *content = "if-modified-since-test";
  21147. {
  21148. std::ofstream ofs(fname);
  21149. ofs << content;
  21150. ASSERT_TRUE(ofs.good());
  21151. }
  21152. Server svr;
  21153. svr.set_mount_point("/static", ".");
  21154. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21155. svr.wait_until_ready();
  21156. Client cli(HOST, PORT);
  21157. // First request: should get 200 with Last-Modified header
  21158. auto res1 = cli.Get("/static/ims_testfile.txt");
  21159. ASSERT_TRUE(res1);
  21160. ASSERT_EQ(200, res1->status);
  21161. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21162. std::string last_modified = res1->get_header_value("Last-Modified");
  21163. EXPECT_FALSE(last_modified.empty());
  21164. // If-Modified-Since with same time: expect 304
  21165. Headers h2 = {{"If-Modified-Since", last_modified}};
  21166. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21167. ASSERT_TRUE(res2);
  21168. EXPECT_EQ(304, res2->status);
  21169. // If-Modified-Since with future time: expect 304
  21170. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21171. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21172. ASSERT_TRUE(res3);
  21173. EXPECT_EQ(304, res3->status);
  21174. // If-Modified-Since with past time: expect 200
  21175. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21176. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21177. ASSERT_TRUE(res4);
  21178. EXPECT_EQ(200, res4->status);
  21179. // If-None-Match takes precedence over If-Modified-Since
  21180. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21181. ASSERT_TRUE(res1->has_header("ETag"));
  21182. std::string etag = res1->get_header_value("ETag");
  21183. Headers h5 = {{"If-None-Match", etag},
  21184. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21185. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21186. ASSERT_TRUE(res5);
  21187. EXPECT_EQ(304, res5->status);
  21188. svr.stop();
  21189. t.join();
  21190. std::remove(fname);
  21191. }
  21192. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21193. using namespace httplib;
  21194. Server svr;
  21195. // Endpoint that returns compressible content
  21196. svr.Get("/compressible", [](const Request &, Response &res) {
  21197. // Return a large enough body to trigger compression
  21198. std::string body(1000, 'a');
  21199. res.set_content(body, "text/plain");
  21200. });
  21201. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21202. svr.wait_until_ready();
  21203. Client cli(HOST, PORT);
  21204. // Request with gzip support: should get Vary header when compressed
  21205. cli.set_compress(true);
  21206. auto res1 = cli.Get("/compressible");
  21207. ASSERT_TRUE(res1);
  21208. EXPECT_EQ(200, res1->status);
  21209. // If Content-Encoding is set, Vary should also be set
  21210. if (res1->has_header("Content-Encoding")) {
  21211. EXPECT_TRUE(res1->has_header("Vary"));
  21212. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21213. }
  21214. // Request without Accept-Encoding header: should not have compression
  21215. Headers h_no_compress;
  21216. auto res2 = cli.Get("/compressible", h_no_compress);
  21217. ASSERT_TRUE(res2);
  21218. EXPECT_EQ(200, res2->status);
  21219. // Verify Vary header is present when compression is applied
  21220. // (the exact behavior depends on server configuration)
  21221. svr.stop();
  21222. t.join();
  21223. }
  21224. TEST(ETagTest, IfRangeWithETag) {
  21225. using namespace httplib;
  21226. // Create a test file with known content
  21227. const char *fname = "if_range_testfile.txt";
  21228. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21229. {
  21230. std::ofstream ofs(fname);
  21231. ofs << content;
  21232. ASSERT_TRUE(ofs.good());
  21233. }
  21234. Server svr;
  21235. svr.set_mount_point("/static", ".");
  21236. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21237. svr.wait_until_ready();
  21238. Client cli(HOST, PORT);
  21239. // First request: get ETag
  21240. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21241. ASSERT_TRUE(res1);
  21242. ASSERT_EQ(200, res1->status);
  21243. ASSERT_TRUE(res1->has_header("ETag"));
  21244. std::string etag = res1->get_header_value("ETag");
  21245. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21246. // Since our server generates weak ETags (W/"..."), If-Range with our
  21247. // ETag should NOT result in partial content - it should return full content.
  21248. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21249. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21250. ASSERT_TRUE(res2);
  21251. // Weak ETag in If-Range -> full content (200), not partial (206)
  21252. EXPECT_EQ(200, res2->status);
  21253. EXPECT_EQ(content, res2->body);
  21254. EXPECT_FALSE(res2->has_header("Content-Range"));
  21255. // Range request with non-matching If-Range (ETag): should get 200 (full
  21256. // content)
  21257. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21258. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21259. ASSERT_TRUE(res3);
  21260. EXPECT_EQ(200, res3->status);
  21261. EXPECT_EQ(content, res3->body);
  21262. EXPECT_FALSE(res3->has_header("Content-Range"));
  21263. // Range request with strong ETag (hypothetical - our server doesn't generate
  21264. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21265. // should return full content)
  21266. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21267. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21268. ASSERT_TRUE(res4);
  21269. EXPECT_EQ(200, res4->status);
  21270. EXPECT_EQ(content, res4->body);
  21271. EXPECT_FALSE(res4->has_header("Content-Range"));
  21272. svr.stop();
  21273. t.join();
  21274. std::remove(fname);
  21275. }
  21276. TEST(ETagTest, IfRangeWithDate) {
  21277. using namespace httplib;
  21278. // Create a test file
  21279. const char *fname = "if_range_date_testfile.txt";
  21280. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21281. {
  21282. std::ofstream ofs(fname);
  21283. ofs << content;
  21284. ASSERT_TRUE(ofs.good());
  21285. }
  21286. Server svr;
  21287. svr.set_mount_point("/static", ".");
  21288. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21289. svr.wait_until_ready();
  21290. Client cli(HOST, PORT);
  21291. // First request: get Last-Modified
  21292. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21293. ASSERT_TRUE(res1);
  21294. ASSERT_EQ(200, res1->status);
  21295. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21296. std::string last_modified = res1->get_header_value("Last-Modified");
  21297. // Range request with matching If-Range (date): should get 206
  21298. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21299. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21300. ASSERT_TRUE(res2);
  21301. EXPECT_EQ(206, res2->status);
  21302. EXPECT_EQ("FGHIJ", res2->body);
  21303. // Range request with old If-Range date: should get 200 (full content)
  21304. Headers h3 = {{"Range", "bytes=5-9"},
  21305. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21306. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21307. ASSERT_TRUE(res3);
  21308. EXPECT_EQ(200, res3->status);
  21309. EXPECT_EQ(content, res3->body);
  21310. // Range request with future If-Range date: should get 206
  21311. Headers h4 = {{"Range", "bytes=0-4"},
  21312. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21313. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21314. ASSERT_TRUE(res4);
  21315. EXPECT_EQ(206, res4->status);
  21316. EXPECT_EQ("ABCDE", res4->body);
  21317. svr.stop();
  21318. t.join();
  21319. std::remove(fname);
  21320. }
  21321. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21322. using namespace httplib;
  21323. const char *fname = "etag_malformed.txt";
  21324. const char *content = "malformed-etag";
  21325. {
  21326. std::ofstream ofs(fname);
  21327. ofs << content;
  21328. ASSERT_TRUE(ofs.good());
  21329. }
  21330. Server svr;
  21331. svr.set_mount_point("/static", ".");
  21332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21333. svr.wait_until_ready();
  21334. Client cli(HOST, PORT);
  21335. // baseline: should get 200 and an ETag
  21336. auto res1 = cli.Get("/static/etag_malformed.txt");
  21337. ASSERT_TRUE(res1);
  21338. ASSERT_EQ(200, res1->status);
  21339. ASSERT_TRUE(res1->has_header("ETag"));
  21340. // Malformed ETag value (missing quotes) should be treated as non-matching
  21341. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21342. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21343. ASSERT_TRUE(res_bad);
  21344. EXPECT_EQ(200, res_bad->status);
  21345. // Whitespace-only header value should be considered invalid / non-matching
  21346. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21347. "Host: localhost\r\n"
  21348. "If-None-Match: \r\n"
  21349. "Connection: close\r\n"
  21350. "\r\n";
  21351. std::string out;
  21352. ASSERT_TRUE(send_request(5, raw_req, &out));
  21353. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21354. svr.stop();
  21355. t.join();
  21356. std::remove(fname);
  21357. }
  21358. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21359. using namespace httplib;
  21360. const char *fname = "ims_invalid_format.txt";
  21361. const char *content = "ims-bad-format";
  21362. {
  21363. std::ofstream ofs(fname);
  21364. ofs << content;
  21365. ASSERT_TRUE(ofs.good());
  21366. }
  21367. Server svr;
  21368. svr.set_mount_point("/static", ".");
  21369. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21370. svr.wait_until_ready();
  21371. Client cli(HOST, PORT);
  21372. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21373. ASSERT_TRUE(res1);
  21374. ASSERT_EQ(200, res1->status);
  21375. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21376. // If-Modified-Since with invalid format should not result in 304
  21377. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21378. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21379. ASSERT_TRUE(res_bad);
  21380. EXPECT_EQ(200, res_bad->status);
  21381. // If-Range with invalid date format should be treated as mismatch -> full
  21382. // content (200)
  21383. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21384. {"If-Range", "invalid-date"}};
  21385. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21386. ASSERT_TRUE(res_ifrange);
  21387. EXPECT_EQ(200, res_ifrange->status);
  21388. svr.stop();
  21389. t.join();
  21390. std::remove(fname);
  21391. }
  21392. TEST(ETagTest, IfRangeWithMalformedETag) {
  21393. using namespace httplib;
  21394. const char *fname = "ifrange_malformed.txt";
  21395. const std::string content = "0123456789";
  21396. {
  21397. std::ofstream ofs(fname);
  21398. ofs << content;
  21399. ASSERT_TRUE(ofs.good());
  21400. }
  21401. Server svr;
  21402. svr.set_mount_point("/static", ".");
  21403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21404. svr.wait_until_ready();
  21405. Client cli(HOST, PORT);
  21406. // First request: get ETag
  21407. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21408. ASSERT_TRUE(res1);
  21409. ASSERT_EQ(200, res1->status);
  21410. ASSERT_TRUE(res1->has_header("ETag"));
  21411. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21412. // full content (200)
  21413. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21414. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21415. ASSERT_TRUE(res2);
  21416. EXPECT_EQ(200, res2->status);
  21417. EXPECT_EQ(content, res2->body);
  21418. svr.stop();
  21419. t.join();
  21420. std::remove(fname);
  21421. }
  21422. TEST(ETagTest, ExtremeLargeDateValues) {
  21423. using namespace httplib;
  21424. const char *fname = "ims_extreme_date.txt";
  21425. const char *content = "ims-extreme-date";
  21426. {
  21427. std::ofstream ofs(fname);
  21428. ofs << content;
  21429. ASSERT_TRUE(ofs.good());
  21430. }
  21431. Server svr;
  21432. svr.set_mount_point("/static", ".");
  21433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21434. svr.wait_until_ready();
  21435. Client cli(HOST, PORT);
  21436. auto res1 = cli.Get(std::string("/static/") + fname);
  21437. ASSERT_TRUE(res1);
  21438. ASSERT_EQ(200, res1->status);
  21439. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21440. // Extremely large year that may overflow date parsing routines.
  21441. Headers h_large_date = {
  21442. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21443. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21444. ASSERT_TRUE(res_bad);
  21445. // Expect server to treat this as invalid/mismatch and return full content
  21446. EXPECT_EQ(200, res_bad->status);
  21447. // If-Range with extremely large date should be treated as mismatch -> full
  21448. // content (200)
  21449. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21450. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21451. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21452. ASSERT_TRUE(res_ifrange);
  21453. EXPECT_EQ(200, res_ifrange->status);
  21454. svr.stop();
  21455. t.join();
  21456. std::remove(fname);
  21457. }
  21458. TEST(ETagTest, NegativeFileModificationTime) {
  21459. using namespace httplib;
  21460. const char *fname = "ims_negative_mtime.txt";
  21461. const std::string content = "negative-mtime";
  21462. {
  21463. std::ofstream ofs(fname);
  21464. ofs << content;
  21465. ASSERT_TRUE(ofs.good());
  21466. }
  21467. // Try to set file mtime to a negative value. This may fail on some
  21468. // platforms/filesystems; if it fails, the test will still verify server
  21469. // behaves safely by performing a regular conditional request.
  21470. #if defined(__APPLE__) || defined(__linux__)
  21471. bool set_negative = false;
  21472. do {
  21473. struct timeval times[2];
  21474. // access time: now
  21475. times[0].tv_sec = time(nullptr);
  21476. times[0].tv_usec = 0;
  21477. // modification time: negative (e.g., -1)
  21478. times[1].tv_sec = -1;
  21479. times[1].tv_usec = 0;
  21480. if (utimes(fname, times) == 0) { set_negative = true; }
  21481. } while (0);
  21482. #else
  21483. bool set_negative = false;
  21484. #endif
  21485. Server svr;
  21486. svr.set_mount_point("/static", ".");
  21487. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21488. svr.wait_until_ready();
  21489. Client cli(HOST, PORT);
  21490. auto res1 = cli.Get(std::string("/static/") + fname);
  21491. ASSERT_TRUE(res1);
  21492. ASSERT_EQ(200, res1->status);
  21493. bool has_last_modified = res1->has_header("Last-Modified");
  21494. std::string last_modified;
  21495. if (has_last_modified) {
  21496. last_modified = res1->get_header_value("Last-Modified");
  21497. }
  21498. if (set_negative) {
  21499. // If we successfully set a negative mtime, ensure server returns a
  21500. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21501. // with an old date and ensure server handles it without crash.
  21502. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21503. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21504. ASSERT_TRUE(res2);
  21505. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21506. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21507. } else {
  21508. // Could not set negative mtime on this platform; fall back to verifying
  21509. // that normal invalid/malformed dates are treated safely (non-304).
  21510. Headers h_bad_date = {
  21511. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21512. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21513. ASSERT_TRUE(res_bad);
  21514. EXPECT_EQ(200, res_bad->status);
  21515. }
  21516. svr.stop();
  21517. t.join();
  21518. std::remove(fname);
  21519. }
  21520. //==============================================================================
  21521. // Integration Tests with Server
  21522. //==============================================================================
  21523. class SSEIntegrationTest : public ::testing::Test {
  21524. protected:
  21525. void SetUp() override {
  21526. stop_server_.store(false);
  21527. events_.clear();
  21528. server_ = httplib::detail::make_unique<Server>();
  21529. setup_server();
  21530. start_server();
  21531. }
  21532. void TearDown() override {
  21533. stop_server_.store(true);
  21534. event_cv_.notify_all();
  21535. server_->stop();
  21536. if (server_thread_.joinable()) { server_thread_.join(); }
  21537. }
  21538. void setup_server() {
  21539. // Simple SSE endpoint
  21540. server_->Get("/events", [this](const Request &req, Response &res) {
  21541. auto last_id = req.get_header_value("Last-Event-ID");
  21542. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21543. res.set_chunked_content_provider(
  21544. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21545. std::unique_lock<std::mutex> lock(event_mutex_);
  21546. if (event_cv_.wait_for(
  21547. lock, std::chrono::milliseconds(200), [this] {
  21548. return !events_.empty() || stop_server_.load();
  21549. })) {
  21550. if (stop_server_.load()) { return false; }
  21551. if (!events_.empty()) {
  21552. std::string event = events_.front();
  21553. events_.erase(events_.begin());
  21554. sink.write(event.data(), event.size());
  21555. return true;
  21556. }
  21557. }
  21558. return !stop_server_.load();
  21559. });
  21560. });
  21561. // Endpoint that returns error
  21562. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21563. res.status = 500;
  21564. res.set_content("Internal Server Error", "text/plain");
  21565. });
  21566. // Endpoint for custom event types
  21567. server_->Get("/custom-events", [](const Request &, Response &res) {
  21568. res.set_chunked_content_provider(
  21569. "text/event-stream", [](size_t offset, DataSink &sink) {
  21570. if (offset == 0) {
  21571. std::string event = "event: update\ndata: updated\n\n"
  21572. "event: delete\ndata: deleted\n\n";
  21573. sink.write(event.data(), event.size());
  21574. }
  21575. return false; // End stream after sending
  21576. });
  21577. });
  21578. }
  21579. void start_server() {
  21580. port_ = server_->bind_to_any_port(HOST);
  21581. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21582. // Wait for server to start
  21583. while (!server_->is_running()) {
  21584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21585. }
  21586. }
  21587. int get_port() const { return port_; }
  21588. void send_event(const std::string &event) {
  21589. std::lock_guard<std::mutex> lock(event_mutex_);
  21590. events_.push_back(event);
  21591. event_cv_.notify_all();
  21592. }
  21593. std::unique_ptr<Server> server_;
  21594. std::thread server_thread_;
  21595. std::mutex event_mutex_;
  21596. std::condition_variable event_cv_;
  21597. std::vector<std::string> events_;
  21598. std::atomic<bool> stop_server_{false};
  21599. std::string last_received_event_id_;
  21600. int port_ = 0;
  21601. };
  21602. //==============================================================================
  21603. // SSE Parsing Tests
  21604. //==============================================================================
  21605. class SSEParsingTest : public SSEIntegrationTest {
  21606. protected:
  21607. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21608. // A trailing sentinel event tells when the whole stream has been parsed.
  21609. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21610. auto body = stream + "event: end\ndata: end\n\n";
  21611. server_->Get("/parse", [body](const Request &, Response &res) {
  21612. res.set_content(body, "text/event-stream");
  21613. });
  21614. return collect("/parse");
  21615. }
  21616. // Runs SSEClient against path until an "end" event arrives and returns the
  21617. // messages dispatched before it
  21618. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21619. Client client(HOST, get_port());
  21620. sse::SSEClient sse(client, path);
  21621. std::mutex mutex;
  21622. std::condition_variable cv;
  21623. std::vector<sse::SSEMessage> messages;
  21624. auto done = false;
  21625. sse.on_message([&](const sse::SSEMessage &msg) {
  21626. std::lock_guard<std::mutex> lock(mutex);
  21627. // Ignore a replay from a reconnect that races with stop()
  21628. if (!done) { messages.push_back(msg); }
  21629. });
  21630. sse.on_event("end", [&](const sse::SSEMessage &) {
  21631. std::lock_guard<std::mutex> lock(mutex);
  21632. done = true;
  21633. cv.notify_all();
  21634. });
  21635. sse.set_reconnect_interval(100);
  21636. sse.start_async();
  21637. {
  21638. std::unique_lock<std::mutex> lock(mutex);
  21639. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21640. }
  21641. sse.stop();
  21642. EXPECT_TRUE(done);
  21643. return messages;
  21644. }
  21645. };
  21646. TEST_F(SSEParsingTest, SingleLineData) {
  21647. auto msgs = parse("data: hello\n\n");
  21648. ASSERT_EQ(msgs.size(), 1u);
  21649. EXPECT_EQ(msgs[0].data, "hello");
  21650. EXPECT_EQ(msgs[0].event, "message");
  21651. }
  21652. TEST_F(SSEParsingTest, MultiLineData) {
  21653. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21654. ASSERT_EQ(msgs.size(), 1u);
  21655. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21656. }
  21657. TEST_F(SSEParsingTest, CustomEventType) {
  21658. auto msgs = parse("event: update\ndata: payload\n\n");
  21659. ASSERT_EQ(msgs.size(), 1u);
  21660. EXPECT_EQ(msgs[0].event, "update");
  21661. EXPECT_EQ(msgs[0].data, "payload");
  21662. }
  21663. TEST_F(SSEParsingTest, EventIdHandling) {
  21664. auto msgs = parse("id: 12345\ndata: test\n\n");
  21665. ASSERT_EQ(msgs.size(), 1u);
  21666. EXPECT_EQ(msgs[0].id, "12345");
  21667. }
  21668. TEST_F(SSEParsingTest, EmptyEventId) {
  21669. auto msgs = parse("id:\ndata: test\n\n");
  21670. ASSERT_EQ(msgs.size(), 1u);
  21671. EXPECT_EQ(msgs[0].id, "");
  21672. }
  21673. TEST_F(SSEParsingTest, CommentsIgnored) {
  21674. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21675. ASSERT_EQ(msgs.size(), 1u);
  21676. EXPECT_EQ(msgs[0].data, "hello");
  21677. EXPECT_EQ(msgs[0].event, "message");
  21678. }
  21679. TEST_F(SSEParsingTest, ColonInValue) {
  21680. auto msgs = parse("data: hello:world:test\n\n");
  21681. ASSERT_EQ(msgs.size(), 1u);
  21682. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21683. }
  21684. TEST_F(SSEParsingTest, FieldNameOnly) {
  21685. // A line without a colon is a field name with an empty value
  21686. auto msgs = parse("data\n\n");
  21687. ASSERT_EQ(msgs.size(), 1u);
  21688. EXPECT_EQ(msgs[0].data, "");
  21689. }
  21690. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21691. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21692. ASSERT_EQ(msgs.size(), 1u);
  21693. EXPECT_EQ(msgs[0].event, "update");
  21694. EXPECT_EQ(msgs[0].data, "hello");
  21695. }
  21696. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21697. auto msgs = parse("data\r\n\r\n");
  21698. ASSERT_EQ(msgs.size(), 1u);
  21699. EXPECT_EQ(msgs[0].data, "");
  21700. }
  21701. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21702. auto msgs = parse("event: update\rdata: hello\r\r");
  21703. ASSERT_EQ(msgs.size(), 1u);
  21704. EXPECT_EQ(msgs[0].event, "update");
  21705. EXPECT_EQ(msgs[0].data, "hello");
  21706. }
  21707. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21708. // Chunk boundaries fall inside every \r\n and right before the first one
  21709. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21710. "\n\r", "\nevent: end\ndata: end\n\n"};
  21711. server_->Get("/split", [chunks](const Request &, Response &res) {
  21712. auto i = std::make_shared<size_t>(0);
  21713. res.set_chunked_content_provider(
  21714. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21715. if (*i == chunks.size()) {
  21716. sink.done();
  21717. } else {
  21718. sink.write(chunks[*i].data(), chunks[*i].size());
  21719. (*i)++;
  21720. }
  21721. return true;
  21722. });
  21723. });
  21724. auto msgs = collect("/split");
  21725. ASSERT_EQ(msgs.size(), 1u);
  21726. EXPECT_EQ(msgs[0].event, "update");
  21727. EXPECT_EQ(msgs[0].data, "hello");
  21728. }
  21729. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21730. // Only a BOM at the start of the stream is ignored
  21731. auto msgs = parse("\xEF\xBB\xBF"
  21732. "data: first\n\n"
  21733. "\xEF\xBB\xBF"
  21734. "data: second\n\n");
  21735. ASSERT_EQ(msgs.size(), 1u);
  21736. EXPECT_EQ(msgs[0].data, "first");
  21737. }
  21738. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21739. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21740. ASSERT_EQ(msgs.size(), 1u);
  21741. EXPECT_EQ(msgs[0].data, "hello");
  21742. EXPECT_EQ(msgs[0].event, "message");
  21743. }
  21744. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21745. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21746. ASSERT_EQ(msgs.size(), 2u);
  21747. EXPECT_EQ(msgs[0].data, "hello");
  21748. EXPECT_EQ(msgs[1].data, "hello");
  21749. }
  21750. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21751. // An event without data is not dispatched, and its type must not leak
  21752. // into the next event
  21753. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21754. ASSERT_EQ(msgs.size(), 1u);
  21755. EXPECT_EQ(msgs[0].event, "message");
  21756. EXPECT_EQ(msgs[0].data, "hello");
  21757. }
  21758. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21759. // Also when the empty field replaces an earlier type
  21760. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21761. ASSERT_EQ(msgs.size(), 2u);
  21762. EXPECT_EQ(msgs[0].event, "message");
  21763. EXPECT_EQ(msgs[1].event, "message");
  21764. }
  21765. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21766. // The first connection sends only an id; the second echoes back the
  21767. // Last-Event-ID it was reconnected with
  21768. std::atomic<int> connection_count{0};
  21769. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21770. if (connection_count++ == 0) {
  21771. res.set_content("id: 42\n\n", "text/event-stream");
  21772. } else {
  21773. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21774. "\n\nevent: end\ndata: end\n\n",
  21775. "text/event-stream");
  21776. }
  21777. });
  21778. auto msgs = collect("/id-only");
  21779. ASSERT_EQ(msgs.size(), 1u);
  21780. EXPECT_EQ(msgs[0].data, "42");
  21781. }
  21782. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21783. // The first connection sets an id and then clears it with an empty one; the
  21784. // second reports whether it was reconnected with a Last-Event-ID
  21785. std::atomic<int> connection_count{0};
  21786. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21787. if (connection_count++ == 0) {
  21788. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21789. "text/event-stream");
  21790. } else {
  21791. res.set_content(
  21792. std::string("data: ") +
  21793. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21794. "\n\nevent: end\ndata: end\n\n",
  21795. "text/event-stream");
  21796. }
  21797. });
  21798. auto msgs = collect("/id-clear");
  21799. ASSERT_EQ(msgs.size(), 3u);
  21800. EXPECT_EQ(msgs[0].id, "1");
  21801. EXPECT_EQ(msgs[1].id, "");
  21802. EXPECT_EQ(msgs[2].data, "not sent");
  21803. }
  21804. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21805. // The first connection sets an id and then sends ids that cannot be carried
  21806. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21807. // with
  21808. std::atomic<int> connection_count{0};
  21809. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21810. if (connection_count++ == 0) {
  21811. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21812. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21813. "text/event-stream");
  21814. } else {
  21815. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21816. "\n\nevent: end\ndata: end\n\n",
  21817. "text/event-stream");
  21818. }
  21819. });
  21820. auto msgs = collect("/id-unsendable");
  21821. ASSERT_EQ(msgs.size(), 1u);
  21822. EXPECT_EQ(msgs[0].data, "42");
  21823. }
  21824. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21825. auto msgs = parse("event: notification\nid: evt-42\n"
  21826. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21827. ASSERT_EQ(msgs.size(), 1u);
  21828. EXPECT_EQ(msgs[0].event, "notification");
  21829. EXPECT_EQ(msgs[0].id, "evt-42");
  21830. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21831. }
  21832. TEST(SSEMessageTest, Clear) {
  21833. sse::SSEMessage msg;
  21834. msg.event = "custom";
  21835. msg.data = "some data";
  21836. msg.id = "123";
  21837. msg.clear();
  21838. EXPECT_EQ(msg.event, "message");
  21839. EXPECT_EQ(msg.data, "");
  21840. EXPECT_EQ(msg.id, "");
  21841. }
  21842. //==============================================================================
  21843. // SSE Integration Tests
  21844. //==============================================================================
  21845. // Test: Successful connection and on_open callback
  21846. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21847. // Add a simple endpoint that sends one event and closes
  21848. server_->Get("/simple-event", [](const Request &, Response &res) {
  21849. res.set_chunked_content_provider(
  21850. "text/event-stream", [](size_t offset, DataSink &sink) {
  21851. if (offset == 0) {
  21852. std::string event = "data: hello\n\n";
  21853. sink.write(event.data(), event.size());
  21854. }
  21855. return false; // Close stream after sending
  21856. });
  21857. });
  21858. Client client("localhost", get_port());
  21859. sse::SSEClient sse(client, "/simple-event");
  21860. std::atomic<bool> open_called{false};
  21861. std::atomic<bool> message_received{false};
  21862. sse.on_open([&open_called]() { open_called.store(true); });
  21863. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21864. if (msg.data == "hello") { message_received.store(true); }
  21865. });
  21866. sse.set_reconnect_interval(100);
  21867. sse.set_max_reconnect_attempts(1);
  21868. // Start async
  21869. sse.start_async();
  21870. // Wait for message to be processed
  21871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21872. sse.stop();
  21873. EXPECT_TRUE(open_called.load());
  21874. EXPECT_TRUE(message_received.load());
  21875. }
  21876. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21877. // A data line that never ends.
  21878. server_->Get("/endless-line", [](const Request &, Response &res) {
  21879. res.set_chunked_content_provider(
  21880. "text/event-stream", [](size_t offset, DataSink &sink) {
  21881. if (offset == 0) { sink.write("data: ", 6); }
  21882. std::string chunk(64 * 1024, 'A');
  21883. return sink.write(chunk.data(), chunk.size());
  21884. });
  21885. });
  21886. Client client("localhost", get_port());
  21887. sse::SSEClient sse(client, "/endless-line");
  21888. std::atomic<bool> too_long{false};
  21889. sse.on_error([&](Error err) {
  21890. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21891. });
  21892. sse.set_max_reconnect_attempts(1);
  21893. sse.start_async();
  21894. for (int i = 0; i < 500 && !too_long; i++) {
  21895. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21896. }
  21897. sse.stop();
  21898. EXPECT_TRUE(too_long);
  21899. }
  21900. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21901. // Far more in all than the client's payload limit below.
  21902. server_->Get("/many-events", [](const Request &, Response &res) {
  21903. res.set_chunked_content_provider(
  21904. "text/event-stream", [](size_t offset, DataSink &sink) {
  21905. if (offset == 0) {
  21906. std::string events;
  21907. for (int i = 0; i < 1000; i++) {
  21908. events += "data: message\n\n";
  21909. }
  21910. sink.write(events.data(), events.size());
  21911. }
  21912. return false;
  21913. });
  21914. });
  21915. Client client("localhost", get_port());
  21916. client.set_payload_max_length(1024);
  21917. sse::SSEClient sse(client, "/many-events");
  21918. std::atomic<int> messages{0};
  21919. std::atomic<bool> too_large{false};
  21920. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21921. sse.on_error([&](Error err) {
  21922. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21923. });
  21924. sse.set_max_reconnect_attempts(1);
  21925. sse.start_async();
  21926. for (int i = 0; i < 500 && messages < 1000; i++) {
  21927. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21928. }
  21929. sse.stop();
  21930. EXPECT_GE(messages.load(), 1000);
  21931. EXPECT_FALSE(too_large);
  21932. }
  21933. // Test: on_message callback
  21934. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21935. // Endpoint that sends multiple events then closes
  21936. server_->Get("/multi-event", [](const Request &, Response &res) {
  21937. res.set_chunked_content_provider(
  21938. "text/event-stream", [](size_t offset, DataSink &sink) {
  21939. if (offset == 0) {
  21940. std::string events = "data: message1\n\ndata: message2\n\n";
  21941. sink.write(events.data(), events.size());
  21942. }
  21943. return false;
  21944. });
  21945. });
  21946. Client client("localhost", get_port());
  21947. sse::SSEClient sse(client, "/multi-event");
  21948. std::vector<std::string> received_messages;
  21949. std::mutex messages_mutex;
  21950. sse.on_message([&](const sse::SSEMessage &msg) {
  21951. std::lock_guard<std::mutex> lock(messages_mutex);
  21952. received_messages.push_back(msg.data);
  21953. });
  21954. sse.set_reconnect_interval(100);
  21955. sse.set_max_reconnect_attempts(1);
  21956. sse.start_async();
  21957. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21958. sse.stop();
  21959. std::lock_guard<std::mutex> lock(messages_mutex);
  21960. EXPECT_GE(received_messages.size(), 2u);
  21961. if (received_messages.size() >= 2) {
  21962. EXPECT_EQ(received_messages[0], "message1");
  21963. EXPECT_EQ(received_messages[1], "message2");
  21964. }
  21965. }
  21966. // Test: on_event for specific types
  21967. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21968. Client client("localhost", get_port());
  21969. sse::SSEClient sse(client, "/custom-events");
  21970. std::atomic<bool> update_received{false};
  21971. std::atomic<bool> delete_received{false};
  21972. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21973. if (msg.data == "updated") { update_received.store(true); }
  21974. });
  21975. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21976. if (msg.data == "deleted") { delete_received.store(true); }
  21977. });
  21978. sse.set_max_reconnect_attempts(1);
  21979. sse.start_async();
  21980. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21981. sse.stop();
  21982. EXPECT_TRUE(update_received.load());
  21983. EXPECT_TRUE(delete_received.load());
  21984. }
  21985. // Test: on_error callback on connection failure
  21986. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21987. // Connect to a non-existent port
  21988. Client client("localhost", 59999);
  21989. sse::SSEClient sse(client, "/events");
  21990. std::atomic<bool> error_called{false};
  21991. Error received_error = Error::Success;
  21992. sse.on_error([&](Error err) {
  21993. error_called.store(true);
  21994. received_error = err;
  21995. });
  21996. sse.set_reconnect_interval(50);
  21997. sse.set_max_reconnect_attempts(1);
  21998. sse.start_async();
  21999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22000. sse.stop();
  22001. EXPECT_TRUE(error_called.load());
  22002. EXPECT_NE(received_error, Error::Success);
  22003. }
  22004. // Test: Last-Event-ID header sent on reconnect
  22005. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22006. // Endpoint that sends event with ID
  22007. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22008. res.set_chunked_content_provider(
  22009. "text/event-stream", [](size_t offset, DataSink &sink) {
  22010. if (offset == 0) {
  22011. std::string event = "id: evt-123\ndata: test\n\n";
  22012. sink.write(event.data(), event.size());
  22013. }
  22014. return false;
  22015. });
  22016. });
  22017. Client client("localhost", get_port());
  22018. sse::SSEClient sse(client, "/event-with-id");
  22019. std::atomic<bool> id_received{false};
  22020. sse.on_message([&](const sse::SSEMessage &msg) {
  22021. if (!msg.id.empty()) { id_received.store(true); }
  22022. });
  22023. sse.set_reconnect_interval(100);
  22024. sse.set_max_reconnect_attempts(1);
  22025. sse.start_async();
  22026. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22027. sse.stop();
  22028. EXPECT_TRUE(id_received.load());
  22029. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22030. }
  22031. // Test: Manual stop
  22032. TEST_F(SSEIntegrationTest, ManualStop) {
  22033. // Endpoint that sends one event and stays open briefly. The server outlives
  22034. // this test body, so the provider uses the fixture's flag, not a local.
  22035. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22036. res.set_chunked_content_provider(
  22037. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22038. if (offset == 0) {
  22039. std::string event = "data: connected\n\n";
  22040. sink.write(event.data(), event.size());
  22041. }
  22042. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22043. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22044. }
  22045. return false;
  22046. });
  22047. });
  22048. Client client("localhost", get_port());
  22049. sse::SSEClient sse(client, "/stay-open");
  22050. std::atomic<bool> connected{false};
  22051. sse.on_open([&connected]() { connected.store(true); });
  22052. sse.set_reconnect_interval(100);
  22053. sse.set_max_reconnect_attempts(1);
  22054. sse.start_async();
  22055. // Wait for connection to establish
  22056. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22057. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22058. }
  22059. EXPECT_TRUE(connected.load());
  22060. EXPECT_TRUE(sse.is_connected());
  22061. // Signal handler to stop
  22062. stop_server_.store(true);
  22063. // Stop SSE client
  22064. sse.stop();
  22065. EXPECT_FALSE(sse.is_connected());
  22066. }
  22067. // Sends one event, then nothing until stop is set
  22068. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22069. return [&stop](const Request &, Response &res) {
  22070. res.set_chunked_content_provider(
  22071. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22072. if (offset == 0) {
  22073. std::string event = "data: hello\n\n";
  22074. sink.write(event.data(), event.size());
  22075. }
  22076. while (!stop.load()) {
  22077. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22078. }
  22079. return false;
  22080. });
  22081. };
  22082. }
  22083. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22084. static void check_stop_interrupts_blocked_read(Client &client) {
  22085. client.set_read_timeout(30, 0);
  22086. for (auto by_destructor : {false, true}) {
  22087. std::atomic<bool> received{false};
  22088. std::chrono::steady_clock::time_point start;
  22089. {
  22090. sse::SSEClient sse(client, "/idle-stream");
  22091. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22092. sse.start_async();
  22093. for (int i = 0; i < 500 && !received.load(); ++i) {
  22094. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22095. }
  22096. ASSERT_TRUE(received.load());
  22097. // Let the client block in the next read
  22098. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22099. start = std::chrono::steady_clock::now();
  22100. if (!by_destructor) { sse.stop(); }
  22101. }
  22102. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22103. std::chrono::seconds(2));
  22104. }
  22105. }
  22106. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22107. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22108. Client client("localhost", get_port());
  22109. check_stop_interrupts_blocked_read(client);
  22110. }
  22111. #ifdef CPPHTTPLIB_SSL_ENABLED
  22112. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22114. std::atomic<bool> done{false};
  22115. svr.Get("/idle-stream", idle_event_stream(done));
  22116. auto port = svr.bind_to_any_port(HOST);
  22117. std::thread t([&] { svr.listen_after_bind(); });
  22118. auto se = detail::scope_exit([&] {
  22119. done.store(true);
  22120. svr.stop();
  22121. t.join();
  22122. });
  22123. svr.wait_until_ready();
  22124. Client client("https://localhost:" + std::to_string(port));
  22125. client.enable_server_certificate_verification(false);
  22126. check_stop_interrupts_blocked_read(client);
  22127. }
  22128. #endif
  22129. // Test: SSEClient with custom headers
  22130. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22131. // Setup a server endpoint that checks for custom header
  22132. std::atomic<bool> header_received{false};
  22133. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22134. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22135. header_received.store(true);
  22136. }
  22137. res.set_chunked_content_provider("text/event-stream",
  22138. [](size_t, DataSink &) { return false; });
  22139. });
  22140. Client client("localhost", get_port());
  22141. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22142. sse::SSEClient sse(client, "/header-check", headers);
  22143. sse.set_max_reconnect_attempts(1);
  22144. sse.start_async();
  22145. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22146. sse.stop();
  22147. EXPECT_TRUE(header_received.load());
  22148. }
  22149. // Test: Reconnect interval configuration
  22150. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22151. Client client("localhost", get_port());
  22152. sse::SSEClient sse(client, "/events");
  22153. auto &result = sse.set_reconnect_interval(500);
  22154. // Builder pattern should return reference to self
  22155. EXPECT_EQ(&result, &sse);
  22156. }
  22157. // Test: Max reconnect attempts
  22158. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22159. // Connect to non-existent port to force reconnects
  22160. Client client("localhost", 59998);
  22161. sse::SSEClient sse(client, "/events");
  22162. std::atomic<int> error_count{0};
  22163. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22164. sse.set_reconnect_interval(50);
  22165. sse.set_max_reconnect_attempts(2);
  22166. auto start = std::chrono::steady_clock::now();
  22167. sse.start(); // Blocking call
  22168. auto end = std::chrono::steady_clock::now();
  22169. // Should have stopped after 2 failed attempts
  22170. EXPECT_GE(error_count.load(), 2);
  22171. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22172. auto duration =
  22173. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22174. #ifdef _WIN32
  22175. // Windows is much slower for socket connection failures
  22176. EXPECT_LT(duration.count(), 7000);
  22177. #else
  22178. EXPECT_LT(duration.count(), 1000);
  22179. #endif
  22180. }
  22181. // Test: Multi-line data in integration
  22182. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22183. // Endpoint with multi-line data
  22184. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22185. res.set_chunked_content_provider(
  22186. "text/event-stream", [](size_t offset, DataSink &sink) {
  22187. if (offset == 0) {
  22188. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22189. sink.write(event.data(), event.size());
  22190. }
  22191. return false;
  22192. });
  22193. });
  22194. Client client("localhost", get_port());
  22195. sse::SSEClient sse(client, "/multiline-data");
  22196. std::string received_data;
  22197. std::mutex data_mutex;
  22198. sse.on_message([&](const sse::SSEMessage &msg) {
  22199. std::lock_guard<std::mutex> lock(data_mutex);
  22200. received_data = msg.data;
  22201. });
  22202. sse.set_reconnect_interval(100);
  22203. sse.set_max_reconnect_attempts(1);
  22204. sse.start_async();
  22205. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22206. sse.stop();
  22207. std::lock_guard<std::mutex> lock(data_mutex);
  22208. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22209. }
  22210. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22211. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22212. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22213. DataSink &sink) {
  22214. if (offset == 0) {
  22215. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22216. sink.write(events.data(), events.size());
  22217. }
  22218. return false;
  22219. });
  22220. });
  22221. Client client("localhost", get_port());
  22222. sse::SSEClient sse(client, "/empty-data-lines");
  22223. std::mutex mutex;
  22224. std::condition_variable cv;
  22225. std::vector<std::string> received;
  22226. sse.on_message([&](const sse::SSEMessage &msg) {
  22227. std::lock_guard<std::mutex> lock(mutex);
  22228. received.push_back(msg.data);
  22229. cv.notify_all();
  22230. });
  22231. sse.set_max_reconnect_attempts(1);
  22232. sse.start_async();
  22233. {
  22234. std::unique_lock<std::mutex> lock(mutex);
  22235. cv.wait_for(lock, std::chrono::seconds(2),
  22236. [&] { return received.size() >= 3; });
  22237. }
  22238. sse.stop();
  22239. ASSERT_GE(received.size(), 3u);
  22240. EXPECT_EQ(received[0], "");
  22241. EXPECT_EQ(received[1], "\nhello");
  22242. EXPECT_EQ(received[2], "");
  22243. }
  22244. // Test: Auto-reconnect after server disconnection
  22245. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22246. std::atomic<int> connection_count{0};
  22247. std::atomic<int> message_count{0};
  22248. // Endpoint that sends one event and closes, forcing reconnect
  22249. server_->Get("/reconnect-test",
  22250. [&connection_count](const Request &, Response &res) {
  22251. connection_count.fetch_add(1);
  22252. res.set_chunked_content_provider(
  22253. "text/event-stream", [](size_t offset, DataSink &sink) {
  22254. if (offset == 0) {
  22255. std::string event = "data: hello\n\n";
  22256. sink.write(event.data(), event.size());
  22257. }
  22258. return false; // Close connection after sending
  22259. });
  22260. });
  22261. Client client("localhost", get_port());
  22262. sse::SSEClient sse(client, "/reconnect-test");
  22263. sse.on_message([&message_count](const sse::SSEMessage &) {
  22264. message_count.fetch_add(1);
  22265. });
  22266. sse.set_reconnect_interval(100);
  22267. sse.set_max_reconnect_attempts(3);
  22268. sse.start_async();
  22269. // Wait long enough for multiple reconnects
  22270. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22271. sse.stop();
  22272. // Should have connected multiple times (initial + reconnects)
  22273. EXPECT_GE(connection_count.load(), 2);
  22274. // Should have received messages from multiple connections
  22275. EXPECT_GE(message_count.load(), 2);
  22276. }
  22277. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22278. std::atomic<int> connection_count{0};
  22279. // Neither Content-Length nor chunked: the close ends the stream
  22280. server_->Get("/close-delimited",
  22281. [&connection_count](const Request &, Response &res) {
  22282. connection_count.fetch_add(1);
  22283. res.set_content_provider(
  22284. "text/event-stream", [](size_t offset, DataSink &sink) {
  22285. if (offset == 0) {
  22286. std::string event = "data: hello\n\n";
  22287. sink.write(event.data(), event.size());
  22288. } else {
  22289. sink.done();
  22290. }
  22291. return true;
  22292. });
  22293. });
  22294. Client client("localhost", get_port());
  22295. sse::SSEClient sse(client, "/close-delimited");
  22296. std::atomic<int> error_count{0};
  22297. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22298. sse.set_reconnect_interval(100);
  22299. sse.start_async();
  22300. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22301. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22302. }
  22303. sse.stop();
  22304. // Reconnects as after any end of the stream, but reports no error
  22305. EXPECT_GE(connection_count.load(), 2);
  22306. EXPECT_EQ(0, error_count.load());
  22307. }
  22308. // Test: A retry field that is not all ASCII digits is ignored
  22309. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22310. std::atomic<int> connection_count{0};
  22311. server_->Get("/bad-retry",
  22312. [&connection_count](const Request &, Response &res) {
  22313. connection_count.fetch_add(1);
  22314. res.set_chunked_content_provider(
  22315. "text/event-stream", [](size_t offset, DataSink &sink) {
  22316. if (offset == 0) {
  22317. std::string event = "retry: -1\ndata: hello\n\n";
  22318. sink.write(event.data(), event.size());
  22319. }
  22320. return false;
  22321. });
  22322. });
  22323. Client client("localhost", get_port());
  22324. sse::SSEClient sse(client, "/bad-retry");
  22325. sse.set_reconnect_interval(10000);
  22326. sse.start_async();
  22327. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22328. sse.stop();
  22329. EXPECT_EQ(connection_count.load(), 1);
  22330. }
  22331. // Test: A retry field of all ASCII digits sets the reconnection time
  22332. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22333. std::mutex mutex;
  22334. std::condition_variable cv;
  22335. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22336. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22337. {
  22338. std::lock_guard<std::mutex> lock(mutex);
  22339. connected_at.push_back(std::chrono::steady_clock::now());
  22340. cv.notify_all();
  22341. }
  22342. res.set_chunked_content_provider(
  22343. "text/event-stream", [](size_t offset, DataSink &sink) {
  22344. if (offset == 0) {
  22345. std::string event = "retry: 0\ndata: hello\n\n";
  22346. sink.write(event.data(), event.size());
  22347. }
  22348. return false;
  22349. });
  22350. });
  22351. Client client("localhost", get_port());
  22352. sse::SSEClient sse(client, "/zero-retry");
  22353. sse.set_reconnect_interval(10000);
  22354. sse.start_async();
  22355. {
  22356. std::unique_lock<std::mutex> lock(mutex);
  22357. cv.wait_for(lock, std::chrono::seconds(5),
  22358. [&] { return connected_at.size() >= 2; });
  22359. }
  22360. sse.stop();
  22361. // The server-supplied interval is applied, but never below 100ms, so
  22362. // "retry: 0" does not cause a busy reconnect loop
  22363. std::lock_guard<std::mutex> lock(mutex);
  22364. ASSERT_GE(connected_at.size(), 2u);
  22365. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22366. connected_at[1] - connected_at[0])
  22367. .count();
  22368. EXPECT_GE(interval_ms, 100);
  22369. }
  22370. // Test: Last-Event-ID sent on reconnect
  22371. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22372. std::atomic<int> connection_count{0};
  22373. std::vector<std::string> received_last_event_ids;
  22374. std::mutex id_mutex;
  22375. // Endpoint that checks Last-Event-ID header and sends event with ID
  22376. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22377. int conn = connection_count.fetch_add(1);
  22378. // Capture the Last-Event-ID header from each connection
  22379. {
  22380. std::lock_guard<std::mutex> lock(id_mutex);
  22381. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22382. }
  22383. res.set_chunked_content_provider(
  22384. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22385. if (offset == 0) {
  22386. std::string event =
  22387. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22388. sink.write(event.data(), event.size());
  22389. }
  22390. return false;
  22391. });
  22392. });
  22393. Client client("localhost", get_port());
  22394. sse::SSEClient sse(client, "/reconnect-with-id");
  22395. sse.set_reconnect_interval(100);
  22396. sse.set_max_reconnect_attempts(3);
  22397. sse.start_async();
  22398. // Wait for at least 2 connections
  22399. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22400. sse.stop();
  22401. // Verify behavior
  22402. std::lock_guard<std::mutex> lock(id_mutex);
  22403. EXPECT_GE(received_last_event_ids.size(), 2u);
  22404. // First connection should have no Last-Event-ID
  22405. if (!received_last_event_ids.empty()) {
  22406. EXPECT_EQ(received_last_event_ids[0], "");
  22407. }
  22408. // Second connection should have Last-Event-ID from first connection
  22409. if (received_last_event_ids.size() >= 2) {
  22410. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22411. }
  22412. }
  22413. // Test: set_headers updates headers used on reconnect
  22414. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22415. std::vector<std::string> received_tokens;
  22416. std::mutex token_mutex;
  22417. // Endpoint that captures Authorization header
  22418. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22419. {
  22420. std::lock_guard<std::mutex> lock(token_mutex);
  22421. received_tokens.push_back(req.get_header_value("Authorization"));
  22422. }
  22423. res.set_chunked_content_provider(
  22424. "text/event-stream", [](size_t offset, DataSink &sink) {
  22425. if (offset == 0) {
  22426. std::string event = "data: hello\n\n";
  22427. sink.write(event.data(), event.size());
  22428. }
  22429. return false; // Close connection to trigger reconnect
  22430. });
  22431. });
  22432. Client client("localhost", get_port());
  22433. Headers headers = {{"Authorization", "Bearer old-token"}};
  22434. sse::SSEClient sse(client, "/auth-check", headers);
  22435. // Update headers on each successful connection
  22436. sse.on_open(
  22437. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22438. sse.set_reconnect_interval(100);
  22439. sse.set_max_reconnect_attempts(3);
  22440. sse.start_async();
  22441. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22442. sse.stop();
  22443. std::lock_guard<std::mutex> lock(token_mutex);
  22444. ASSERT_GE(received_tokens.size(), 2u);
  22445. // First connection uses original header
  22446. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22447. // Second connection uses updated header from set_headers
  22448. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22449. }
  22450. // Test: 401 allows reconnection (so on_error can refresh headers)
  22451. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22452. std::atomic<int> connection_count{0};
  22453. // Endpoint: returns 401 on first attempt, 200 on second
  22454. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22455. int conn = connection_count.fetch_add(1);
  22456. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22457. res.status = StatusCode::Unauthorized_401;
  22458. res.set_content("Unauthorized", "text/plain");
  22459. return;
  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: authenticated\n\n";
  22465. sink.write(event.data(), event.size());
  22466. }
  22467. return false;
  22468. });
  22469. });
  22470. Client client("localhost", get_port());
  22471. Headers headers = {{"Authorization", "Bearer expired"}};
  22472. sse::SSEClient sse(client, "/auth-retry", headers);
  22473. std::atomic<bool> message_received{false};
  22474. // Refresh token on error
  22475. sse.on_error(
  22476. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22477. sse.on_message([&](const sse::SSEMessage &msg) {
  22478. if (msg.data == "authenticated") { message_received.store(true); }
  22479. });
  22480. sse.set_reconnect_interval(100);
  22481. sse.set_max_reconnect_attempts(3);
  22482. sse.start_async();
  22483. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22484. sse.stop();
  22485. // Should have reconnected after 401 and succeeded with new token
  22486. EXPECT_GE(connection_count.load(), 2);
  22487. EXPECT_TRUE(message_received.load());
  22488. }
  22489. TEST(Issue2318Test, EmptyHostString) {
  22490. {
  22491. httplib::Client cli_empty("", PORT);
  22492. auto res = cli_empty.Get("/");
  22493. ASSERT_FALSE(res);
  22494. EXPECT_EQ(httplib::Error::Connection, res.error());
  22495. }
  22496. {
  22497. httplib::Client cli(" ", PORT);
  22498. auto res = cli.Get("/");
  22499. ASSERT_FALSE(res);
  22500. EXPECT_EQ(httplib::Error::Connection, res.error());
  22501. }
  22502. }
  22503. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22504. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22505. Server svr;
  22506. // Set a small payload limit (1KB)
  22507. svr.set_payload_max_length(1024);
  22508. svr.Post("/test", [&](const Request &req, Response &res) {
  22509. res.set_content("Body size: " + std::to_string(req.body.size()),
  22510. "text/plain");
  22511. });
  22512. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22513. auto se = detail::scope_exit([&] {
  22514. svr.stop();
  22515. listen_thread.join();
  22516. });
  22517. svr.wait_until_ready();
  22518. // Create data that compresses well but exceeds limit when decompressed
  22519. // 8KB of repeated null bytes compresses to a very small size
  22520. std::string original_data(8 * 1024, '\0');
  22521. // Compress the data using gzip
  22522. std::string compressed_data;
  22523. detail::gzip_compressor compressor;
  22524. compressor.compress(original_data.data(), original_data.size(), true,
  22525. [&](const char *data, size_t size) {
  22526. compressed_data.append(data, size);
  22527. return true;
  22528. });
  22529. // Verify compression worked (compressed should be much smaller)
  22530. ASSERT_LT(compressed_data.size(), original_data.size());
  22531. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22532. // Send compressed data with Content-Encoding: gzip
  22533. Client cli(HOST, PORT);
  22534. Headers headers = {{"Content-Encoding", "gzip"}};
  22535. auto res =
  22536. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22537. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22539. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22540. }
  22541. #endif
  22542. // ============================================================================
  22543. // OpenSSL-Specific Tests
  22544. // ============================================================================
  22545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22546. X509 *readCertificate(const std::string &strFileName) {
  22547. std::ifstream inStream(strFileName);
  22548. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22549. std::istreambuf_iterator<char>());
  22550. if (strCertPEM.empty()) return (nullptr);
  22551. BIO *pbCert = BIO_new(BIO_s_mem());
  22552. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22553. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22554. BIO_free(pbCert);
  22555. return (pCert);
  22556. }
  22557. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22558. std::ifstream inStream(strFileName);
  22559. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22560. std::istreambuf_iterator<char>());
  22561. if (strPrivateKeyPEM.empty()) return (nullptr);
  22562. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22563. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22564. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22565. BIO_free(pbPrivKey);
  22566. return (pPrivateKey);
  22567. }
  22568. TEST(BindServerTest, UpdateCerts) {
  22569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22570. int port = svr.bind_to_any_port("0.0.0.0");
  22571. ASSERT_TRUE(svr.is_valid());
  22572. ASSERT_TRUE(port > 0);
  22573. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22574. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22575. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22576. ASSERT_TRUE(cert != nullptr);
  22577. ASSERT_TRUE(ca_cert != nullptr);
  22578. ASSERT_TRUE(key != nullptr);
  22579. X509_STORE *cert_store = X509_STORE_new();
  22580. X509_STORE_add_cert(cert_store, ca_cert);
  22581. // svr.update_certs(cert, key, cert_store); // deprecated
  22582. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22583. CLIENT_CA_CERT_FILE);
  22584. ASSERT_TRUE(svr.is_valid());
  22585. svr.stop();
  22586. X509_STORE_free(cert_store);
  22587. X509_free(cert);
  22588. X509_free(ca_cert);
  22589. EVP_PKEY_free(key);
  22590. }
  22591. // Test that update_certs() updates client CA list correctly
  22592. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22593. // Start with file-based constructor
  22594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22595. ASSERT_TRUE(svr.is_valid());
  22596. // Initially no client CA list should be set
  22597. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22598. ASSERT_TRUE(ssl_ctx != nullptr);
  22599. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22600. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22601. // Now update with client CA (PEM string)
  22602. std::string cert_pem, key_pem, ca_pem;
  22603. read_file(SERVER_CERT_FILE, cert_pem);
  22604. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22605. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22606. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22607. ASSERT_TRUE(svr.is_valid());
  22608. // Now client CA list should be set
  22609. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22610. ASSERT_TRUE(ca_list_after != nullptr);
  22611. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22612. }
  22613. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22614. // Test that the file-path SSLServer constructor properly sets the client CA
  22615. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22617. ASSERT_TRUE(svr.is_valid());
  22618. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22619. ASSERT_TRUE(ssl_ctx != nullptr);
  22620. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22621. ASSERT_TRUE(ca_list != nullptr);
  22622. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22623. }
  22624. #endif
  22625. // ============================================================================
  22626. // MbedTLS-Specific Tests
  22627. // ============================================================================
  22628. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22629. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22630. using namespace httplib::tls;
  22631. // Track if callback was invoked
  22632. bool callback_invoked = false;
  22633. // The callback receives void* ctx which is actually MbedTlsContext*
  22634. // We can access the mbedtls_ssl_config via the context
  22635. auto setup_callback = [&callback_invoked](void *ctx) {
  22636. callback_invoked = true;
  22637. // Cast to MbedTlsContext* to access the ssl config
  22638. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22639. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22640. // Use static variables to hold certificate data (simplified for test)
  22641. static mbedtls_x509_crt own_cert;
  22642. static mbedtls_pk_context own_key;
  22643. static mbedtls_x509_crt ca_chain;
  22644. static bool initialized = false;
  22645. if (!initialized) {
  22646. mbedtls_x509_crt_init(&own_cert);
  22647. mbedtls_pk_init(&own_key);
  22648. mbedtls_x509_crt_init(&ca_chain);
  22649. // Load server certificate
  22650. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22651. return false;
  22652. }
  22653. // Load server private key.
  22654. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22655. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22656. #if MBEDTLS_VERSION_MAJOR == 3
  22657. ,
  22658. mbedtls_ctr_drbg_random, nullptr
  22659. #endif
  22660. ) != 0) {
  22661. return false;
  22662. }
  22663. // Load CA chain for client verification
  22664. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22665. return false;
  22666. }
  22667. initialized = true;
  22668. }
  22669. // Configure the SSL config
  22670. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22671. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22672. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22673. // Set minimum TLS version using mbedTLS native API
  22674. #if MBEDTLS_VERSION_MAJOR >= 3
  22675. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22676. #else
  22677. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22678. MBEDTLS_SSL_MINOR_VERSION_3);
  22679. #endif
  22680. return true;
  22681. };
  22682. SSLServer svr(setup_callback);
  22683. ASSERT_TRUE(svr.is_valid());
  22684. ASSERT_TRUE(callback_invoked);
  22685. svr.Get("/test", [&](const Request &req, Response &res) {
  22686. res.set_content("test", "text/plain");
  22687. auto cert = req.peer_cert();
  22688. ASSERT_TRUE(static_cast<bool>(cert));
  22689. auto common_name = cert.subject_cn();
  22690. EXPECT_EQ("Common Name", common_name);
  22691. });
  22692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22693. auto se = detail::scope_exit([&] {
  22694. svr.stop();
  22695. t.join();
  22696. ASSERT_FALSE(svr.is_running());
  22697. });
  22698. svr.wait_until_ready();
  22699. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22700. cli.enable_server_certificate_verification(false);
  22701. cli.set_connection_timeout(30);
  22702. auto res = cli.Get("/test");
  22703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22704. ASSERT_EQ(StatusCode::OK_200, res->status);
  22705. }
  22706. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22707. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22708. // keep-alive SSL session, which reads through that config in
  22709. // mbedtls_ssl_close_notify.
  22710. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22712. ASSERT_TRUE(svr.is_valid());
  22713. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22714. res.set_content("test", "text/plain");
  22715. });
  22716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22717. auto se = detail::scope_exit([&] {
  22718. svr.stop();
  22719. t.join();
  22720. ASSERT_FALSE(svr.is_running());
  22721. });
  22722. svr.wait_until_ready();
  22723. {
  22724. SSLClient cli(HOST, PORT);
  22725. cli.enable_server_certificate_verification(false);
  22726. cli.set_keep_alive(true);
  22727. auto res = cli.Get("/test");
  22728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22729. ASSERT_EQ(StatusCode::OK_200, res->status);
  22730. // cli is destructed here with the keep-alive SSL session still open.
  22731. }
  22732. }
  22733. #endif
  22734. // WebSocket Tests
  22735. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22736. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22737. // defining the meaning of these bits has been negotiated.
  22738. auto make_frame = [](uint8_t first_byte) {
  22739. std::string frame;
  22740. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22741. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22742. frame += "Hello";
  22743. return frame;
  22744. };
  22745. // RSV1 set (0x40)
  22746. {
  22747. detail::BufferStream strm;
  22748. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22749. ws::Opcode opcode;
  22750. std::string payload;
  22751. bool fin;
  22752. EXPECT_EQ(
  22753. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22754. ws::impl::FrameRead::Fail);
  22755. }
  22756. // RSV2 set (0x20)
  22757. {
  22758. detail::BufferStream strm;
  22759. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22760. ws::Opcode opcode;
  22761. std::string payload;
  22762. bool fin;
  22763. EXPECT_EQ(
  22764. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22765. ws::impl::FrameRead::Fail);
  22766. }
  22767. // RSV3 set (0x10)
  22768. {
  22769. detail::BufferStream strm;
  22770. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22771. ws::Opcode opcode;
  22772. std::string payload;
  22773. bool fin;
  22774. EXPECT_EQ(
  22775. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22776. ws::impl::FrameRead::Fail);
  22777. }
  22778. // No RSV bits set - should succeed
  22779. {
  22780. detail::BufferStream strm;
  22781. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22782. ws::Opcode opcode;
  22783. std::string payload;
  22784. bool fin;
  22785. EXPECT_EQ(
  22786. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22787. ws::impl::FrameRead::Ok);
  22788. EXPECT_EQ(ws::Opcode::Text, opcode);
  22789. EXPECT_EQ("Hello", payload);
  22790. EXPECT_TRUE(fin);
  22791. }
  22792. }
  22793. TEST(WebSocketTest, ControlFrameValidation) {
  22794. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22795. // payload length <= 125.
  22796. // Ping with FIN=0 - must be rejected
  22797. {
  22798. detail::BufferStream strm;
  22799. std::string frame;
  22800. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22801. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22802. strm.write(frame.data(), frame.size());
  22803. ws::Opcode opcode;
  22804. std::string payload;
  22805. bool fin;
  22806. EXPECT_EQ(
  22807. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22808. ws::impl::FrameRead::Fail);
  22809. }
  22810. // Close with FIN=0 - must be rejected
  22811. {
  22812. detail::BufferStream strm;
  22813. std::string frame;
  22814. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22815. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22816. strm.write(frame.data(), frame.size());
  22817. ws::Opcode opcode;
  22818. std::string payload;
  22819. bool fin;
  22820. EXPECT_EQ(
  22821. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22822. ws::impl::FrameRead::Fail);
  22823. }
  22824. // Ping with payload_len=126 (extended length) - must be rejected
  22825. {
  22826. detail::BufferStream strm;
  22827. std::string frame;
  22828. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22829. frame += static_cast<char>(126); // payload_len=126 (>125)
  22830. frame += static_cast<char>(0x00); // extended length high byte
  22831. frame += static_cast<char>(126); // extended length low byte
  22832. frame += std::string(126, 'x');
  22833. strm.write(frame.data(), frame.size());
  22834. ws::Opcode opcode;
  22835. std::string payload;
  22836. bool fin;
  22837. EXPECT_EQ(
  22838. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22839. ws::impl::FrameRead::Fail);
  22840. }
  22841. // Ping with FIN=1 and payload_len=125 - should succeed
  22842. {
  22843. detail::BufferStream strm;
  22844. std::string frame;
  22845. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22846. frame += static_cast<char>(125); // payload_len=125
  22847. frame += std::string(125, 'x');
  22848. strm.write(frame.data(), frame.size());
  22849. ws::Opcode opcode;
  22850. std::string payload;
  22851. bool fin;
  22852. EXPECT_EQ(
  22853. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22854. ws::impl::FrameRead::Ok);
  22855. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22856. EXPECT_EQ(125u, payload.size());
  22857. EXPECT_TRUE(fin);
  22858. }
  22859. }
  22860. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22861. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22862. // length MUST be 0.
  22863. // MSB set - must be rejected
  22864. {
  22865. detail::BufferStream strm;
  22866. std::string frame;
  22867. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22868. frame += static_cast<char>(127); // 64-bit extended length
  22869. frame += static_cast<char>(0x80); // MSB set (invalid)
  22870. frame += std::string(7, '\0'); // remaining 7 bytes of length
  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. // MSB clear - should pass length parsing (will be rejected by max_len,
  22880. // but that's a different check; use a small length to verify)
  22881. {
  22882. detail::BufferStream strm;
  22883. std::string frame;
  22884. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22885. frame += static_cast<char>(127); // 64-bit extended length
  22886. frame += std::string(7, '\0'); // high bytes = 0
  22887. frame += static_cast<char>(0x03); // length = 3
  22888. frame += "abc";
  22889. strm.write(frame.data(), frame.size());
  22890. ws::Opcode opcode;
  22891. std::string payload;
  22892. bool fin;
  22893. EXPECT_EQ(
  22894. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22895. ws::impl::FrameRead::Ok);
  22896. EXPECT_EQ(ws::Opcode::Text, opcode);
  22897. EXPECT_EQ("abc", payload);
  22898. }
  22899. }
  22900. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22901. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22902. // Valid UTF-8
  22903. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22904. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22905. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22906. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22907. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22908. // Invalid UTF-8
  22909. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22910. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22911. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22912. EXPECT_FALSE(
  22913. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22914. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22915. }
  22916. TEST(WebSocketTest, ConnectAndDisconnect) {
  22917. Server svr;
  22918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22919. std::string msg;
  22920. while (ws.read(msg)) {}
  22921. });
  22922. auto port = svr.bind_to_any_port(HOST);
  22923. std::thread t([&]() { svr.listen_after_bind(); });
  22924. svr.wait_until_ready();
  22925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22926. auto res = client.connect();
  22927. ASSERT_TRUE(res);
  22928. EXPECT_EQ(Error::Success, res.error());
  22929. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22930. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22931. EXPECT_TRUE(client.is_open());
  22932. client.close();
  22933. EXPECT_FALSE(client.is_open());
  22934. svr.stop();
  22935. t.join();
  22936. }
  22937. TEST(WebSocketTest, ValidURL) {
  22938. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22939. EXPECT_TRUE(ws1.is_valid());
  22940. ws::WebSocketClient ws2("ws://example.com/path");
  22941. EXPECT_TRUE(ws2.is_valid());
  22942. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22943. EXPECT_TRUE(ws3.is_valid());
  22944. #ifdef CPPHTTPLIB_SSL_ENABLED
  22945. ws::WebSocketClient wss1("wss://example.com/path");
  22946. EXPECT_TRUE(wss1.is_valid());
  22947. ws::WebSocketClient wss2("wss://example.com:443/path");
  22948. EXPECT_TRUE(wss2.is_valid());
  22949. #endif
  22950. }
  22951. TEST(WebSocketTest, InvalidURL) {
  22952. // No scheme
  22953. ws::WebSocketClient ws1("localhost:8080/path");
  22954. EXPECT_FALSE(ws1.is_valid());
  22955. // No path
  22956. ws::WebSocketClient ws2("ws://localhost:8080");
  22957. EXPECT_FALSE(ws2.is_valid());
  22958. // Empty string
  22959. ws::WebSocketClient ws3("");
  22960. EXPECT_FALSE(ws3.is_valid());
  22961. // Missing host
  22962. ws::WebSocketClient ws4("ws://:8080/path");
  22963. EXPECT_FALSE(ws4.is_valid());
  22964. // Port number overflow — should not crash
  22965. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22966. EXPECT_FALSE(ws5.is_valid());
  22967. // Port out of range
  22968. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22969. EXPECT_FALSE(ws6.is_valid());
  22970. }
  22971. TEST(WebSocketTest, UnsupportedScheme) {
  22972. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22973. ws::WebSocketClient ws1("http://localhost:8080/path");
  22974. EXPECT_FALSE(ws1.is_valid());
  22975. ws::WebSocketClient ws2("https://localhost:8080/path");
  22976. EXPECT_FALSE(ws2.is_valid());
  22977. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22978. EXPECT_FALSE(ws3.is_valid());
  22979. #else
  22980. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22981. std::invalid_argument);
  22982. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22983. std::invalid_argument);
  22984. #endif
  22985. }
  22986. TEST(WebSocketTest, ConnectWhenInvalid) {
  22987. ws::WebSocketClient ws("not a valid url");
  22988. EXPECT_FALSE(ws.is_valid());
  22989. auto res = ws.connect();
  22990. EXPECT_FALSE(res);
  22991. EXPECT_EQ(Error::Connection, res.error());
  22992. EXPECT_EQ(-1, res.status());
  22993. }
  22994. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22995. // Grab a port that is free, then close it again so nothing listens there
  22996. Server svr;
  22997. auto port = svr.bind_to_any_port(HOST);
  22998. svr.stop();
  22999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23000. auto res = client.connect();
  23001. ASSERT_FALSE(res);
  23002. EXPECT_EQ(Error::Connection, res.error());
  23003. EXPECT_EQ(-1, res.status());
  23004. }
  23005. TEST(WebSocketTest, DefaultPort) {
  23006. ws::WebSocketClient ws1("ws://example.com/path");
  23007. EXPECT_TRUE(ws1.is_valid());
  23008. // ws:// defaults to port 80 (verified by successful parse)
  23009. #ifdef CPPHTTPLIB_SSL_ENABLED
  23010. ws::WebSocketClient ws2("wss://example.com/path");
  23011. EXPECT_TRUE(ws2.is_valid());
  23012. // wss:// defaults to port 443 (verified by successful parse)
  23013. #endif
  23014. }
  23015. TEST(WebSocketTest, IPv6LiteralAddress) {
  23016. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23017. EXPECT_TRUE(ws1.is_valid());
  23018. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23019. EXPECT_TRUE(ws2.is_valid());
  23020. }
  23021. TEST(WebSocketTest, ComplexPath) {
  23022. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23023. EXPECT_TRUE(ws1.is_valid());
  23024. ws::WebSocketClient ws2("ws://localhost:8080/");
  23025. EXPECT_TRUE(ws2.is_valid());
  23026. }
  23027. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23028. Server svr;
  23029. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23030. std::string msg;
  23031. while (ws.read(msg)) {}
  23032. });
  23033. auto port = svr.bind_to_any_port(HOST);
  23034. std::thread t([&]() { svr.listen_after_bind(); });
  23035. svr.wait_until_ready();
  23036. auto another_host = "example.com";
  23037. auto wrong_ip = "192.0.2.1";
  23038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23039. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23040. ASSERT_TRUE(client.connect());
  23041. EXPECT_TRUE(client.is_open());
  23042. client.close();
  23043. svr.stop();
  23044. t.join();
  23045. }
  23046. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23047. Server svr;
  23048. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23049. std::string msg;
  23050. while (ws.read(msg)) {}
  23051. });
  23052. auto port = svr.bind_to_any_port(HOST);
  23053. std::thread t([&]() { svr.listen_after_bind(); });
  23054. svr.wait_until_ready();
  23055. auto wrong_ip = "192.0.2.1";
  23056. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23057. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23058. client.set_connection_timeout(1);
  23059. client.set_read_timeout(1);
  23060. client.set_write_timeout(1);
  23061. EXPECT_FALSE(client.connect());
  23062. EXPECT_FALSE(client.is_open());
  23063. svr.stop();
  23064. t.join();
  23065. }
  23066. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23067. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23068. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23069. // (RFC 6761) is only a map key and the Host header value.
  23070. auto host = "target.invalid";
  23071. Server svr;
  23072. std::string received_host;
  23073. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23074. received_host = req.get_header_value("Host");
  23075. std::string msg;
  23076. while (ws.read(msg)) {}
  23077. });
  23078. auto port = svr.bind_to_any_port(HOST);
  23079. std::thread t([&]() { svr.listen_after_bind(); });
  23080. // ASSERT_* below returns from the test body, which would leave t joinable
  23081. // and make ~thread call std::terminate.
  23082. auto se = detail::scope_exit([&] {
  23083. svr.stop();
  23084. if (t.joinable()) { t.join(); }
  23085. });
  23086. svr.wait_until_ready();
  23087. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23088. std::to_string(port) + "/ws");
  23089. client.set_hostname_addr_map({{host, HOST}});
  23090. ASSERT_TRUE(client.connect());
  23091. EXPECT_TRUE(client.is_open());
  23092. client.close();
  23093. svr.stop();
  23094. t.join();
  23095. // The mapping only redirects the connection; the identity stays host_.
  23096. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23097. }
  23098. class WebSocketIntegrationTest : public ::testing::Test {
  23099. protected:
  23100. void SetUp() override {
  23101. server_ = httplib::detail::make_unique<Server>();
  23102. setup_server();
  23103. start_server();
  23104. }
  23105. void TearDown() override {
  23106. server_->stop();
  23107. if (server_thread_.joinable()) { server_thread_.join(); }
  23108. }
  23109. void setup_server() {
  23110. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23111. std::string msg;
  23112. ws::ReadResult ret;
  23113. while ((ret = ws.read(msg))) {
  23114. if (ret == ws::Binary) {
  23115. ws.send(msg.data(), msg.size());
  23116. } else {
  23117. ws.send(msg);
  23118. }
  23119. }
  23120. });
  23121. server_->WebSocket("/ws-echo-string",
  23122. [](const Request &, ws::WebSocket &ws) {
  23123. std::string msg;
  23124. while (ws.read(msg)) {
  23125. ws.send("echo: " + msg);
  23126. }
  23127. });
  23128. server_->WebSocket(
  23129. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23130. // Echo back request metadata
  23131. ws.send("path:" + req.path);
  23132. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23133. std::string msg;
  23134. while (ws.read(msg)) {}
  23135. });
  23136. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23137. std::string msg;
  23138. ws.read(msg); // wait for a message
  23139. ws.close();
  23140. });
  23141. server_->WebSocket("/ws-close-status",
  23142. [](const Request &, ws::WebSocket &ws) {
  23143. std::string msg;
  23144. ws.read(msg); // wait for a message
  23145. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23146. });
  23147. server_->WebSocket(
  23148. "/ws-subprotocol",
  23149. [](const Request &, ws::WebSocket &ws) {
  23150. std::string msg;
  23151. while (ws.read(msg)) {
  23152. ws.send(msg);
  23153. }
  23154. },
  23155. [](const std::vector<std::string> &protocols) -> std::string {
  23156. for (const auto &p : protocols) {
  23157. if (p == "graphql-ws") { return p; }
  23158. }
  23159. return "";
  23160. });
  23161. server_->WebSocket(
  23162. "/ws-subprotocol-unoffered",
  23163. [](const Request &, ws::WebSocket &ws) {
  23164. std::string msg;
  23165. while (ws.read(msg)) {
  23166. ws.send(msg);
  23167. }
  23168. },
  23169. [](const std::vector<std::string> &) -> std::string {
  23170. return "admin";
  23171. });
  23172. }
  23173. void start_server() {
  23174. port_ = server_->bind_to_any_port(HOST);
  23175. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23176. server_->wait_until_ready();
  23177. }
  23178. std::unique_ptr<Server> server_;
  23179. std::thread server_thread_;
  23180. int port_ = 0;
  23181. };
  23182. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23183. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23184. "/ws-echo");
  23185. ASSERT_TRUE(client.connect());
  23186. ASSERT_TRUE(client.is_open());
  23187. ASSERT_TRUE(client.send("Hello WebSocket"));
  23188. std::string msg;
  23189. EXPECT_EQ(ws::Text, client.read(msg));
  23190. EXPECT_EQ("Hello WebSocket", msg);
  23191. client.close();
  23192. }
  23193. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23194. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23195. "/ws-echo");
  23196. ASSERT_TRUE(client.connect());
  23197. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23198. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23199. std::string msg;
  23200. EXPECT_EQ(ws::Binary, client.read(msg));
  23201. EXPECT_EQ(binary_data, msg);
  23202. client.close();
  23203. }
  23204. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23206. "/ws-echo");
  23207. ASSERT_TRUE(client.connect());
  23208. for (int i = 0; i < 10; i++) {
  23209. auto text = "message " + std::to_string(i);
  23210. ASSERT_TRUE(client.send(text));
  23211. std::string msg;
  23212. ASSERT_TRUE(client.read(msg));
  23213. EXPECT_EQ(text, msg);
  23214. }
  23215. client.close();
  23216. }
  23217. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23219. "/ws-close");
  23220. ASSERT_TRUE(client.connect());
  23221. // Send a message to trigger the server to close
  23222. ASSERT_TRUE(client.send("trigger close"));
  23223. // The server will close, so read should return false
  23224. std::string msg;
  23225. EXPECT_FALSE(client.read(msg));
  23226. EXPECT_FALSE(client.is_open());
  23227. }
  23228. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23230. "/ws-echo");
  23231. ASSERT_TRUE(client.connect());
  23232. // 128KB message
  23233. std::string large_data(128 * 1024, 'X');
  23234. ASSERT_TRUE(client.send(large_data));
  23235. std::string msg;
  23236. ASSERT_TRUE(client.read(msg));
  23237. EXPECT_EQ(large_data, msg);
  23238. client.close();
  23239. }
  23240. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23242. "/ws-echo");
  23243. ASSERT_TRUE(client.connect());
  23244. const int num_threads = 4;
  23245. std::vector<std::thread> threads;
  23246. std::atomic<int> send_count{0};
  23247. for (int t = 0; t < num_threads; t++) {
  23248. threads.emplace_back([&client, &send_count, t]() {
  23249. for (int i = 0; i < 5; i++) {
  23250. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23251. if (client.send(text)) { send_count++; }
  23252. }
  23253. });
  23254. }
  23255. for (auto &th : threads) {
  23256. th.join();
  23257. }
  23258. int received = 0;
  23259. std::string msg;
  23260. while (received < send_count.load()) {
  23261. if (!client.read(msg)) { break; }
  23262. received++;
  23263. }
  23264. EXPECT_EQ(send_count.load(), received);
  23265. client.close();
  23266. }
  23267. TEST_F(WebSocketIntegrationTest, ReadString) {
  23268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23269. "/ws-echo-string");
  23270. ASSERT_TRUE(client.connect());
  23271. ASSERT_TRUE(client.send("hello"));
  23272. std::string msg;
  23273. ASSERT_TRUE(client.read(msg));
  23274. EXPECT_EQ("echo: hello", msg);
  23275. ASSERT_TRUE(client.send("world"));
  23276. ASSERT_TRUE(client.read(msg));
  23277. EXPECT_EQ("echo: world", msg);
  23278. client.close();
  23279. }
  23280. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23281. Headers headers = {{"X-Test-Header", "test-value"}};
  23282. ws::WebSocketClient client(
  23283. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23284. ASSERT_TRUE(client.connect());
  23285. std::string msg;
  23286. ASSERT_TRUE(client.read(msg));
  23287. EXPECT_EQ("path:/ws-request-info", msg);
  23288. ASSERT_TRUE(client.read(msg));
  23289. EXPECT_EQ("header:test-value", msg);
  23290. client.close();
  23291. }
  23292. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23294. "/ws-echo");
  23295. client.set_read_timeout(1, 0); // 1 second
  23296. ASSERT_TRUE(client.connect());
  23297. // Don't send anything — server echo handler waits for a message, so read()
  23298. // should time out. The connection survives it: nothing was consumed.
  23299. std::string msg;
  23300. EXPECT_EQ(client.read(msg), ws::Timeout);
  23301. EXPECT_TRUE(client.is_open());
  23302. // And it is still usable afterwards.
  23303. EXPECT_TRUE(client.send("after timeout"));
  23304. EXPECT_EQ(client.read(msg), ws::Text);
  23305. EXPECT_EQ(msg, "after timeout");
  23306. }
  23307. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23309. "/ws-echo");
  23310. client.set_read_timeout(1, 0);
  23311. ASSERT_TRUE(client.connect());
  23312. ASSERT_TRUE(client.send("first"));
  23313. std::string msg;
  23314. ASSERT_EQ(client.read(msg), ws::Text);
  23315. ASSERT_EQ(msg, "first");
  23316. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23317. // not be used with a read timeout: it would reprocess the previous message.
  23318. EXPECT_EQ(client.read(msg), ws::Timeout);
  23319. EXPECT_EQ(msg, "first");
  23320. }
  23321. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23322. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23323. "/ws-echo");
  23324. ASSERT_TRUE(client.connect());
  23325. // Setting it once the connection is open reaches the live stream, not just
  23326. // the seed for the next connect().
  23327. client.set_read_timeout(1, 0);
  23328. std::string msg;
  23329. EXPECT_EQ(client.read(msg), ws::Timeout);
  23330. EXPECT_TRUE(client.is_open());
  23331. }
  23332. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23334. "/ws-echo");
  23335. client.set_read_timeout(5, 0);
  23336. ASSERT_TRUE(client.connect());
  23337. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23338. // The server should reject it and close the connection.
  23339. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23340. client.send(oversized);
  23341. // The server's read() should have failed due to payload limit,
  23342. // so our read() should return false (connection closed).
  23343. std::string msg;
  23344. EXPECT_FALSE(client.read(msg));
  23345. }
  23346. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23347. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23348. "/ws-echo");
  23349. client.set_read_timeout(10, 0);
  23350. ASSERT_TRUE(client.connect());
  23351. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23352. // This should succeed.
  23353. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23354. ASSERT_TRUE(client.send(at_limit));
  23355. std::string msg;
  23356. ASSERT_TRUE(client.read(msg));
  23357. EXPECT_EQ(at_limit.size(), msg.size());
  23358. client.close();
  23359. }
  23360. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23362. "/nonexistent");
  23363. auto res = client.connect();
  23364. EXPECT_FALSE(res);
  23365. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23366. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23367. EXPECT_FALSE(client.is_open());
  23368. }
  23369. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23371. "/ws-echo");
  23372. ASSERT_TRUE(client.connect());
  23373. ASSERT_TRUE(client.send(""));
  23374. std::string msg;
  23375. EXPECT_EQ(ws::Text, client.read(msg));
  23376. EXPECT_EQ("", msg);
  23377. client.close();
  23378. }
  23379. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23381. "/ws-echo");
  23382. // First connection
  23383. ASSERT_TRUE(client.connect());
  23384. ASSERT_TRUE(client.send("first"));
  23385. std::string msg;
  23386. ASSERT_TRUE(client.read(msg));
  23387. EXPECT_EQ("first", msg);
  23388. client.close();
  23389. EXPECT_FALSE(client.is_open());
  23390. // Reconnect using the same client object
  23391. ASSERT_TRUE(client.connect());
  23392. ASSERT_TRUE(client.is_open());
  23393. ASSERT_TRUE(client.send("second"));
  23394. ASSERT_TRUE(client.read(msg));
  23395. EXPECT_EQ("second", msg);
  23396. client.close();
  23397. }
  23398. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23400. "/ws-close-status");
  23401. ASSERT_TRUE(client.connect());
  23402. // Trigger the server to close with GoingAway status
  23403. ASSERT_TRUE(client.send("trigger"));
  23404. // read() should return false after receiving the close frame
  23405. std::string msg;
  23406. EXPECT_FALSE(client.read(msg));
  23407. EXPECT_FALSE(client.is_open());
  23408. }
  23409. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23411. "/ws-echo");
  23412. ASSERT_TRUE(client.connect());
  23413. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23414. EXPECT_FALSE(client.is_open());
  23415. }
  23416. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23417. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23418. ws::WebSocketClient client(
  23419. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23420. ASSERT_TRUE(client.connect());
  23421. // Server should have selected graphql-ws
  23422. EXPECT_EQ("graphql-ws", client.subprotocol());
  23423. client.close();
  23424. }
  23425. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23426. Headers headers;
  23427. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23428. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23429. ws::WebSocketClient client(
  23430. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23431. ASSERT_TRUE(client.connect());
  23432. // The offer on the second field line counts too, so graphql-ws is selected
  23433. EXPECT_EQ("graphql-ws", client.subprotocol());
  23434. client.close();
  23435. }
  23436. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23437. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23438. ws::WebSocketClient client(
  23439. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23440. ASSERT_TRUE(client.connect());
  23441. // Server should not have selected any subprotocol
  23442. EXPECT_TRUE(client.subprotocol().empty());
  23443. client.close();
  23444. }
  23445. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23446. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23448. "/ws-subprotocol-unoffered",
  23449. headers);
  23450. ASSERT_TRUE(client.connect());
  23451. EXPECT_TRUE(client.subprotocol().empty());
  23452. client.close();
  23453. }
  23454. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23455. // Connect without requesting any subprotocol
  23456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23457. "/ws-subprotocol");
  23458. ASSERT_TRUE(client.connect());
  23459. EXPECT_TRUE(client.subprotocol().empty());
  23460. client.close();
  23461. }
  23462. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23464. "/ws-echo");
  23465. client.set_tcp_nodelay(true);
  23466. client.set_connection_timeout(3, 0);
  23467. bool socket_options_called = false;
  23468. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23469. ASSERT_TRUE(client.connect());
  23470. ASSERT_TRUE(client.is_open());
  23471. EXPECT_TRUE(socket_options_called);
  23472. ASSERT_TRUE(client.send("hello"));
  23473. std::string msg;
  23474. auto result = client.read(msg);
  23475. EXPECT_EQ(result, ws::ReadResult::Text);
  23476. EXPECT_EQ(msg, "hello");
  23477. client.close();
  23478. }
  23479. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23481. "/ws-echo");
  23482. client.set_connection_timeout(std::chrono::seconds(3));
  23483. client.set_write_timeout(std::chrono::seconds(3));
  23484. // A sub-second remainder exercises the seconds/microseconds split.
  23485. client.set_read_timeout(std::chrono::milliseconds(1500));
  23486. ASSERT_TRUE(client.connect());
  23487. auto start = std::chrono::steady_clock::now();
  23488. std::string msg;
  23489. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23490. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23491. std::chrono::steady_clock::now() - start)
  23492. .count();
  23493. // Above 1s so that dropping the microseconds half of the split fails here.
  23494. // Ignoring the setter altogether would not reach this line at all: a client
  23495. // waits forever by default.
  23496. EXPECT_GE(elapsed, 1400);
  23497. EXPECT_LT(elapsed, 30000);
  23498. }
  23499. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23500. Server svr;
  23501. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23502. if (!req.has_header("Authorization")) {
  23503. res.status = StatusCode::Unauthorized_401;
  23504. res.set_content("Unauthorized", "text/plain");
  23505. return Server::HandlerResponse::Handled;
  23506. }
  23507. return Server::HandlerResponse::Unhandled;
  23508. });
  23509. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23510. std::string msg;
  23511. while (ws.read(msg)) {
  23512. ws.send(msg);
  23513. }
  23514. });
  23515. auto port = svr.bind_to_any_port("localhost");
  23516. std::thread t([&]() { svr.listen_after_bind(); });
  23517. svr.wait_until_ready();
  23518. // Without Authorization header - should be rejected before upgrade
  23519. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23520. EXPECT_FALSE(client1.connect());
  23521. // The rejection is framed like any other HTTP response
  23522. {
  23523. Client cli("localhost", port);
  23524. Headers headers = {{"Upgrade", "websocket"},
  23525. {"Connection", "Upgrade"},
  23526. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23527. {"Sec-WebSocket-Version", "13"}};
  23528. auto res = cli.Get("/ws", headers);
  23529. ASSERT_TRUE(res);
  23530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23531. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23532. EXPECT_EQ("Unauthorized", res->body);
  23533. }
  23534. // With Authorization header - should succeed
  23535. Headers headers = {{"Authorization", "Bearer token123"}};
  23536. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23537. headers);
  23538. ASSERT_TRUE(client2.connect());
  23539. ASSERT_TRUE(client2.send("hello"));
  23540. std::string msg;
  23541. ASSERT_TRUE(client2.read(msg));
  23542. EXPECT_EQ("hello", msg);
  23543. client2.close();
  23544. svr.stop();
  23545. t.join();
  23546. }
  23547. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23548. Server svr;
  23549. std::atomic<int> pre_routing_calls{0};
  23550. std::atomic<int> pre_request_calls{0};
  23551. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23552. pre_routing_calls++;
  23553. if (req.path == "/handled") {
  23554. res.set_content("handled", "text/plain");
  23555. return Server::HandlerResponse::Handled;
  23556. }
  23557. return Server::HandlerResponse::Unhandled;
  23558. });
  23559. svr.set_pre_request_handler([&](const Request &, Response &) {
  23560. pre_request_calls++;
  23561. return Server::HandlerResponse::Unhandled;
  23562. });
  23563. svr.Get("/http", [](const Request &, Response &res) {
  23564. res.set_content("http", "text/plain");
  23565. });
  23566. svr.WebSocket("/ws",
  23567. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23568. auto port = svr.bind_to_any_port("localhost");
  23569. std::thread t([&]() { svr.listen_after_bind(); });
  23570. auto se = detail::scope_exit([&] {
  23571. svr.stop();
  23572. t.join();
  23573. });
  23574. svr.wait_until_ready();
  23575. Headers upgrade = {{"Upgrade", "websocket"},
  23576. {"Connection", "Upgrade"},
  23577. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23578. {"Sec-WebSocket-Version", "13"}};
  23579. auto get = [&](const char *path) {
  23580. pre_routing_calls = 0;
  23581. return Client("localhost", port).Get(path, upgrade);
  23582. };
  23583. // No WebSocket route, but an HTTP one
  23584. auto res = get("/http");
  23585. ASSERT_TRUE(res);
  23586. EXPECT_EQ(StatusCode::OK_200, res->status);
  23587. EXPECT_EQ("http", res->body);
  23588. EXPECT_EQ(1, pre_routing_calls);
  23589. EXPECT_EQ(1, pre_request_calls);
  23590. // No route at all
  23591. res = get("/none");
  23592. ASSERT_TRUE(res);
  23593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23594. EXPECT_EQ(1, pre_routing_calls);
  23595. // Answered by the pre-routing handler
  23596. res = get("/handled");
  23597. ASSERT_TRUE(res);
  23598. EXPECT_EQ(StatusCode::OK_200, res->status);
  23599. EXPECT_EQ("handled", res->body);
  23600. EXPECT_EQ(1, pre_routing_calls);
  23601. // A WebSocket route
  23602. pre_routing_calls = 0;
  23603. pre_request_calls = 0;
  23604. {
  23605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23606. "/ws");
  23607. ASSERT_TRUE(client.connect());
  23608. std::string msg;
  23609. ASSERT_TRUE(client.read(msg));
  23610. EXPECT_EQ("ws", msg);
  23611. client.close();
  23612. }
  23613. EXPECT_EQ(1, pre_routing_calls);
  23614. EXPECT_EQ(1, pre_request_calls);
  23615. }
  23616. // An upgrade request answered by a hook leaves its body unread, so that body
  23617. // must not be served as the next request on the connection.
  23618. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23619. Server svr;
  23620. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23621. if (req.path == "/pre-routing") {
  23622. res.set_content("pre-routing", "text/plain");
  23623. return Server::HandlerResponse::Handled;
  23624. }
  23625. return Server::HandlerResponse::Unhandled;
  23626. });
  23627. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23628. if (req.matched_route == "/pre-request") {
  23629. res.set_content("pre-request", "text/plain");
  23630. return Server::HandlerResponse::Handled;
  23631. }
  23632. return Server::HandlerResponse::Unhandled;
  23633. });
  23634. svr.Get("/smuggled", [](const Request &, Response &res) {
  23635. res.set_content("smuggled", "text/plain");
  23636. });
  23637. svr.WebSocket("/pre-request",
  23638. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23639. auto port = svr.bind_to_any_port(HOST);
  23640. std::thread t([&]() { svr.listen_after_bind(); });
  23641. auto se = detail::scope_exit([&] {
  23642. svr.stop();
  23643. t.join();
  23644. });
  23645. svr.wait_until_ready();
  23646. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23647. for (auto path : {"/pre-routing", "/pre-request"}) {
  23648. std::string req = std::string("GET ") + path +
  23649. " HTTP/1.1\r\n"
  23650. "Host: localhost\r\n"
  23651. "Upgrade: websocket\r\n"
  23652. "Connection: Upgrade\r\n"
  23653. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23654. "Sec-WebSocket-Version: 13\r\n"
  23655. "Content-Length: " +
  23656. std::to_string(body.size()) + "\r\n\r\n" + body;
  23657. std::string res;
  23658. ASSERT_TRUE(send_request(5, req, &res, port));
  23659. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23660. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23661. // Only one response, and the body was not served as a request
  23662. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23663. }
  23664. }
  23665. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23666. Server svr;
  23667. std::atomic<int> pre_request_calls{0};
  23668. std::atomic<bool> route_matched{false};
  23669. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23670. pre_request_calls++;
  23671. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23672. if (req.get_header_value("Authorization") != "Bearer token123") {
  23673. res.status = StatusCode::Unauthorized_401;
  23674. res.set_content("Unauthorized", "text/plain");
  23675. return Server::HandlerResponse::Handled;
  23676. }
  23677. return Server::HandlerResponse::Unhandled;
  23678. });
  23679. std::atomic<bool> handler_called{false};
  23680. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23681. handler_called = true;
  23682. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23683. });
  23684. auto port = svr.bind_to_any_port("localhost");
  23685. std::thread t([&]() { svr.listen_after_bind(); });
  23686. svr.wait_until_ready();
  23687. // Without Authorization header - should be rejected before upgrade
  23688. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23689. "/ws/1");
  23690. EXPECT_FALSE(client1.connect());
  23691. EXPECT_FALSE(handler_called);
  23692. EXPECT_EQ(1, pre_request_calls);
  23693. EXPECT_TRUE(route_matched);
  23694. // The rejection is an ordinary HTTP response, not a protocol switch
  23695. {
  23696. Client cli("localhost", port);
  23697. Headers headers = {{"Upgrade", "websocket"},
  23698. {"Connection", "Upgrade"},
  23699. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23700. {"Sec-WebSocket-Version", "13"}};
  23701. auto res = cli.Get("/ws/1", headers);
  23702. ASSERT_TRUE(res);
  23703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23704. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23705. EXPECT_EQ("Unauthorized", res->body);
  23706. }
  23707. EXPECT_FALSE(handler_called);
  23708. // With Authorization header - should succeed
  23709. Headers headers = {{"Authorization", "Bearer token123"}};
  23710. ws::WebSocketClient client2(
  23711. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23712. ASSERT_TRUE(client2.connect());
  23713. std::string msg;
  23714. ASSERT_TRUE(client2.read(msg));
  23715. EXPECT_EQ("/ws/:id 2", msg);
  23716. EXPECT_TRUE(handler_called);
  23717. client2.close();
  23718. svr.stop();
  23719. t.join();
  23720. }
  23721. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23722. static Headers websocket_upgrade_headers() {
  23723. return {{"Upgrade", "websocket"},
  23724. {"Connection", "Upgrade"},
  23725. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23726. {"Sec-WebSocket-Version", "13"},
  23727. {"Sec-WebSocket-Protocol", "chat"}};
  23728. }
  23729. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23730. Server svr;
  23731. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23732. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23733. return Server::HandlerResponse::Unhandled;
  23734. });
  23735. svr.set_pre_request_handler([](const Request &req, Response &) {
  23736. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23737. return Server::HandlerResponse::Unhandled;
  23738. });
  23739. svr.set_exception_handler(
  23740. [](const Request &, Response &res, std::exception_ptr ep) {
  23741. try {
  23742. std::rethrow_exception(ep);
  23743. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23744. });
  23745. auto handler = [](const Request &, ws::WebSocket &) {};
  23746. svr.WebSocket("/pre-routing", handler);
  23747. svr.WebSocket("/pre-request", handler);
  23748. svr.WebSocket("/sub-protocol", handler,
  23749. [](const std::vector<std::string> &) -> std::string {
  23750. throw std::runtime_error("/sub-protocol");
  23751. });
  23752. auto port = svr.bind_to_any_port(HOST);
  23753. ASSERT_GT(port, 0);
  23754. thread t = thread([&] { svr.listen_after_bind(); });
  23755. auto se = detail::scope_exit([&] {
  23756. svr.stop();
  23757. t.join();
  23758. ASSERT_FALSE(svr.is_running());
  23759. });
  23760. svr.wait_until_ready();
  23761. Client cli(HOST, port);
  23762. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23763. auto res = cli.Get(path, websocket_upgrade_headers());
  23764. if (!res) {
  23765. ADD_FAILURE() << path << ": " << to_string(res.error());
  23766. continue;
  23767. }
  23768. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23769. EXPECT_EQ(path, res->body);
  23770. }
  23771. }
  23772. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23773. Server svr;
  23774. svr.set_pre_routing_handler(
  23775. [](const Request &, Response &) -> Server::HandlerResponse {
  23776. throw std::runtime_error("pre-routing");
  23777. });
  23778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23779. auto port = svr.bind_to_any_port(HOST);
  23780. ASSERT_GT(port, 0);
  23781. thread t = thread([&] { svr.listen_after_bind(); });
  23782. auto se = detail::scope_exit([&] {
  23783. svr.stop();
  23784. t.join();
  23785. ASSERT_FALSE(svr.is_running());
  23786. });
  23787. svr.wait_until_ready();
  23788. Client cli(HOST, port);
  23789. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23790. ASSERT_TRUE(res) << to_string(res.error());
  23791. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23792. }
  23793. #endif
  23794. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23795. Server svr;
  23796. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23797. // A read timeout is how a handler gets control back. Without it, a handler
  23798. // parked in read() can never write on the connection it is reading.
  23799. ws.set_read_timeout(std::chrono::milliseconds(100));
  23800. std::string msg;
  23801. while (ws.is_open()) {
  23802. auto r = ws.read(msg);
  23803. if (r == httplib::ws::Timeout) {
  23804. ws.send("tick");
  23805. continue;
  23806. }
  23807. if (r == httplib::ws::Fail) { break; }
  23808. ws.send(msg);
  23809. }
  23810. });
  23811. auto port = svr.bind_to_any_port("localhost");
  23812. std::thread t([&]() { svr.listen_after_bind(); });
  23813. svr.wait_until_ready();
  23814. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23815. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23816. ASSERT_TRUE(client.connect());
  23817. // The client sends nothing, so anything it receives came out of the
  23818. // handler's timeout path.
  23819. std::string msg;
  23820. ASSERT_EQ(client.read(msg), ws::Text);
  23821. EXPECT_EQ("tick", msg);
  23822. client.close();
  23823. svr.stop();
  23824. t.join();
  23825. }
  23826. // Stream::read may return fewer bytes than asked for. This is that contract at
  23827. // its worst -- one byte per call -- which is what a frame header straddling a
  23828. // read buffer's boundary looks like to the frame parser.
  23829. class WsByteAtATimeStream : public Stream {
  23830. public:
  23831. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23832. bool is_readable() const override { return true; }
  23833. bool wait_readable() const override { return true; }
  23834. bool wait_writable() const override { return true; }
  23835. ssize_t read(char *ptr, size_t size) override {
  23836. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23837. *ptr = data_[pos_++];
  23838. return 1;
  23839. }
  23840. ssize_t write(const char *, size_t size) override {
  23841. return static_cast<ssize_t>(size);
  23842. }
  23843. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23844. ip = "127.0.0.1";
  23845. port = 0;
  23846. }
  23847. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23848. ip = "127.0.0.1";
  23849. port = 0;
  23850. }
  23851. socket_t socket() const override { return INVALID_SOCKET; }
  23852. time_t duration() const override { return 0; }
  23853. private:
  23854. std::string data_;
  23855. size_t pos_ = 0;
  23856. };
  23857. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23858. // The payload uses the 16-bit extended length, so the header, the length
  23859. // and the mask key are all multi-byte fields here. Each used to be read
  23860. // with a single read() call, which fails as soon as one is split. The
  23861. // payload is also a little over one read chunk, so it is read in two.
  23862. std::string body;
  23863. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23864. body += static_cast<char>(i % 251);
  23865. }
  23866. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23867. std::string frame;
  23868. frame += static_cast<char>(0x81); // FIN + Text
  23869. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23870. frame += static_cast<char>(body.size() >> 8);
  23871. frame += static_cast<char>(body.size() & 0xff);
  23872. for (size_t i = 0; i < 4; i++) {
  23873. frame += static_cast<char>(mask[i]);
  23874. }
  23875. for (size_t i = 0; i < body.size(); i++) {
  23876. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23877. }
  23878. WsByteAtATimeStream strm(frame);
  23879. ws::Opcode opcode;
  23880. std::string payload;
  23881. bool fin = false;
  23882. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23883. /*expect_masked=*/true, body.size()),
  23884. ws::impl::FrameRead::Ok);
  23885. EXPECT_TRUE(fin);
  23886. EXPECT_EQ(opcode, ws::Opcode::Text);
  23887. EXPECT_EQ(payload, body);
  23888. }
  23889. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23890. std::string body(2000, 'x');
  23891. std::string frame;
  23892. frame += static_cast<char>(0x82); // FIN + Binary
  23893. frame += static_cast<char>(126); // 16-bit length follows
  23894. frame += static_cast<char>(body.size() >> 8);
  23895. frame += static_cast<char>(body.size() & 0xff);
  23896. frame += body;
  23897. detail::BufferStream strm;
  23898. strm.write(frame.data(), frame.size());
  23899. ws::Opcode opcode;
  23900. std::string payload;
  23901. bool fin;
  23902. EXPECT_EQ(
  23903. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23904. ws::impl::FrameRead::Ok);
  23905. EXPECT_EQ(body, payload);
  23906. }
  23907. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23908. // The header announces the largest payload allowed, and only 3 bytes of it
  23909. // ever arrive.
  23910. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23911. std::string frame;
  23912. frame += static_cast<char>(0x82); // FIN + Binary
  23913. frame += static_cast<char>(127); // 64-bit length follows
  23914. for (int shift = 56; shift >= 0; shift -= 8) {
  23915. frame += static_cast<char>((len >> shift) & 0xff);
  23916. }
  23917. frame += "abc";
  23918. detail::BufferStream strm;
  23919. strm.write(frame.data(), frame.size());
  23920. ws::Opcode opcode;
  23921. std::string payload;
  23922. bool fin;
  23923. EXPECT_EQ(
  23924. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23925. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23926. ws::impl::FrameRead::Fail);
  23927. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23928. }
  23929. TEST(WebSocketTest, QueryStringInHandshake) {
  23930. Server svr;
  23931. std::mutex mtx;
  23932. std::string received_target;
  23933. std::string received_token;
  23934. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23935. {
  23936. std::lock_guard<std::mutex> lock(mtx);
  23937. received_target = req.target;
  23938. if (req.has_param("token")) {
  23939. received_token = req.get_param_value("token");
  23940. }
  23941. }
  23942. std::string msg;
  23943. while (ws.read(msg)) {
  23944. ws.send(msg);
  23945. }
  23946. });
  23947. auto port = svr.bind_to_any_port("localhost");
  23948. std::thread t([&]() { svr.listen_after_bind(); });
  23949. svr.wait_until_ready();
  23950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23951. "/ws?token=ABC&session=123");
  23952. ASSERT_TRUE(client.connect());
  23953. // Round-trip ensures the handler has run and captured the request.
  23954. ASSERT_TRUE(client.send("hello"));
  23955. std::string msg;
  23956. ASSERT_TRUE(client.read(msg));
  23957. EXPECT_EQ("hello", msg);
  23958. client.close();
  23959. {
  23960. std::lock_guard<std::mutex> lock(mtx);
  23961. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23962. EXPECT_EQ("ABC", received_token);
  23963. }
  23964. svr.stop();
  23965. t.join();
  23966. }
  23967. // Run a handshake against a throwaway server and hand the request the server
  23968. // received back to the caller, so tests can assert on the headers the client
  23969. // actually put on the wire.
  23970. static void capture_websocket_handshake_request(
  23971. const Headers &client_headers,
  23972. std::function<void(const Request &, int port)> verify) {
  23973. Server svr;
  23974. std::mutex mtx;
  23975. Request received;
  23976. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23977. {
  23978. std::lock_guard<std::mutex> lock(mtx);
  23979. received = req;
  23980. }
  23981. std::string msg;
  23982. while (ws.read(msg)) {
  23983. ws.send(msg);
  23984. }
  23985. });
  23986. auto port = svr.bind_to_any_port("localhost");
  23987. std::thread t([&]() { svr.listen_after_bind(); });
  23988. auto se = detail::scope_exit([&] {
  23989. svr.stop();
  23990. t.join();
  23991. });
  23992. svr.wait_until_ready();
  23993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23994. client_headers);
  23995. ASSERT_TRUE(client.connect());
  23996. ASSERT_TRUE(client.send("hello"));
  23997. std::string msg;
  23998. ASSERT_TRUE(client.read(msg));
  23999. client.close();
  24000. {
  24001. std::lock_guard<std::mutex> lock(mtx);
  24002. verify(received, port);
  24003. }
  24004. }
  24005. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24006. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24007. // Non-default port must be present in the Host header. Default ports
  24008. // (80/443) are omitted; that logic is covered by
  24009. // MakeHostAndPortStringTest.
  24010. EXPECT_EQ("localhost:" + std::to_string(port),
  24011. req.get_header_value("Host"));
  24012. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24013. req.get_header_value("User-Agent"));
  24014. EXPECT_FALSE(req.has_header("Accept"));
  24015. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24016. EXPECT_FALSE(req.has_header("Content-Length"));
  24017. });
  24018. }
  24019. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24020. capture_websocket_handshake_request(
  24021. {{"Host", "example.com"},
  24022. {"User-Agent", "custom-agent"},
  24023. {"X-Custom", "value"}},
  24024. [](const Request &req, int) {
  24025. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24026. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24027. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24028. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24029. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24030. });
  24031. }
  24032. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24033. capture_websocket_handshake_request(
  24034. {{"Upgrade", "bogus"},
  24035. {"Connection", "close"},
  24036. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24037. {"Sec-WebSocket-Version", "8"}},
  24038. [](const Request &req, int) {
  24039. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24040. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24041. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24042. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24043. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24044. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24045. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24046. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24047. req.get_header_value("Sec-WebSocket-Key"));
  24048. });
  24049. }
  24050. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24051. // A header the client refuses to send must abort the handshake before any
  24052. // part of it reaches the wire; a lone request line would otherwise sit in
  24053. // the peer's buffer as a truncated request.
  24054. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24055. ASSERT_NE(INVALID_SOCKET, srv);
  24056. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24057. sockaddr_in addr{};
  24058. addr.sin_family = AF_INET;
  24059. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24060. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24061. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24062. ASSERT_EQ(0, ::listen(srv, 1));
  24063. sockaddr_in bound{};
  24064. socklen_t bound_len = sizeof(bound);
  24065. ASSERT_EQ(
  24066. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24067. auto port = ntohs(bound.sin_port);
  24068. ssize_t received = -1;
  24069. std::thread t([&] {
  24070. // Bound every blocking call so a regression fails the test with a bad
  24071. // value instead of hanging the suite.
  24072. fd_set rfds;
  24073. FD_ZERO(&rfds);
  24074. FD_SET(srv, &rfds);
  24075. timeval tv{5, 0};
  24076. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24077. 0) {
  24078. return;
  24079. }
  24080. sockaddr_in cli_addr{};
  24081. socklen_t cli_len = sizeof(cli_addr);
  24082. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24083. if (cli == INVALID_SOCKET) { return; }
  24084. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24085. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24086. char buf[4096];
  24087. received = ::recv(cli, buf, sizeof(buf), 0);
  24088. });
  24089. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24090. // connect() has already shut the socket down by the time it returns false,
  24091. // so the peer sees EOF without waiting for the client to be destroyed.
  24092. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24093. {{"X-Bad", "a\r\nInjected: 1"}});
  24094. EXPECT_FALSE(client.connect());
  24095. t.join();
  24096. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24097. EXPECT_EQ(0, received);
  24098. }
  24099. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24100. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24101. // contains "upgrade" as a substring is a different token and must not
  24102. // start a WebSocket handshake.
  24103. auto make_request = [](const std::vector<std::string> &connection_values) {
  24104. Request req;
  24105. req.method = "GET";
  24106. req.headers.emplace("Upgrade", "websocket");
  24107. for (const auto &value : connection_values) {
  24108. req.headers.emplace("Connection", value);
  24109. }
  24110. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24111. req.headers.emplace("Sec-WebSocket-Version", "13");
  24112. return req;
  24113. };
  24114. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24115. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24116. EXPECT_TRUE(
  24117. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24118. EXPECT_TRUE(
  24119. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24120. EXPECT_TRUE(
  24121. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24122. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24123. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24124. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24125. EXPECT_FALSE(
  24126. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24127. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24128. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24129. }
  24130. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24131. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24132. // asks recipients to match each protocol-name case-insensitively, and RFC
  24133. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24134. // client naming websocket alongside another protocol, or on a second field
  24135. // line, is offering websocket; a value that merely contains "websocket" as a
  24136. // substring is a different protocol name and is not.
  24137. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24138. Request req;
  24139. req.method = "GET";
  24140. for (const auto &value : upgrade_values) {
  24141. req.headers.emplace("Upgrade", value);
  24142. }
  24143. req.headers.emplace("Connection", "Upgrade");
  24144. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24145. req.headers.emplace("Sec-WebSocket-Version", "13");
  24146. return req;
  24147. };
  24148. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24149. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24150. EXPECT_TRUE(
  24151. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24152. EXPECT_TRUE(
  24153. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24154. EXPECT_TRUE(
  24155. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24156. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24157. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24158. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24159. EXPECT_FALSE(
  24160. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24161. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24162. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24163. }
  24164. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24165. Server svr;
  24166. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24167. auto port = svr.bind_to_any_port("localhost");
  24168. std::thread t([&]() { svr.listen_after_bind(); });
  24169. auto se = detail::scope_exit([&] {
  24170. svr.stop();
  24171. t.join();
  24172. });
  24173. svr.wait_until_ready();
  24174. Headers headers = {{"Upgrade", "websocket"},
  24175. {"Connection", "notupgrade"},
  24176. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24177. {"Sec-WebSocket-Version", "13"}};
  24178. Client cli("localhost", port);
  24179. auto res = cli.Get("/ws", headers);
  24180. // The route exists only as a WebSocket route, so a request that fails the
  24181. // handshake check falls through to ordinary routing.
  24182. ASSERT_TRUE(res);
  24183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24184. }
  24185. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24186. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24187. // Connection value is the only thing left for the client to reject.
  24188. Server svr;
  24189. svr.Get("/ws", [](const Request &req, Response &res) {
  24190. res.status = StatusCode::SwitchingProtocol_101;
  24191. res.set_header("Upgrade", "websocket");
  24192. res.set_header("Connection", "notupgrade");
  24193. res.set_header("Sec-WebSocket-Accept",
  24194. detail::websocket_accept_key(
  24195. req.get_header_value("Sec-WebSocket-Key")));
  24196. });
  24197. auto port = svr.bind_to_any_port("localhost");
  24198. std::thread t([&]() { svr.listen_after_bind(); });
  24199. auto se = detail::scope_exit([&] {
  24200. svr.stop();
  24201. t.join();
  24202. });
  24203. svr.wait_until_ready();
  24204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24205. auto res = client.connect();
  24206. EXPECT_FALSE(res);
  24207. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24208. EXPECT_FALSE(client.is_open());
  24209. }
  24210. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24211. Server svr;
  24212. svr.Get("/ws", [](const Request &req, Response &res) {
  24213. res.status = StatusCode::SwitchingProtocol_101;
  24214. res.set_header("Upgrade", "websocket");
  24215. res.set_header("Connection", "Upgrade");
  24216. res.set_header("Sec-WebSocket-Accept",
  24217. detail::websocket_accept_key(
  24218. req.get_header_value("Sec-WebSocket-Key")));
  24219. res.set_header("Sec-WebSocket-Protocol", "admin");
  24220. });
  24221. auto port = svr.bind_to_any_port("localhost");
  24222. std::thread t([&]() { svr.listen_after_bind(); });
  24223. auto se = detail::scope_exit([&] {
  24224. svr.stop();
  24225. t.join();
  24226. });
  24227. svr.wait_until_ready();
  24228. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24229. // Server selects a subprotocol the client never offered
  24230. {
  24231. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24232. ws::WebSocketClient client(url, headers);
  24233. auto res = client.connect();
  24234. EXPECT_FALSE(res);
  24235. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24236. EXPECT_FALSE(client.is_open());
  24237. EXPECT_TRUE(client.subprotocol().empty());
  24238. }
  24239. // Client offered none but the server named one anyway
  24240. {
  24241. ws::WebSocketClient client(url);
  24242. auto res = client.connect();
  24243. EXPECT_FALSE(res);
  24244. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24245. EXPECT_FALSE(client.is_open());
  24246. EXPECT_TRUE(client.subprotocol().empty());
  24247. }
  24248. }
  24249. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24250. // The socket path doubles as the URL host, so it must not contain '/'.
  24251. const char *shard = getenv("GTEST_SHARD_INDEX");
  24252. const std::string sock_path =
  24253. shard ? std::string("httplib-ws-") + shard + ".sock"
  24254. : std::string("httplib-ws.sock");
  24255. std::remove(sock_path.c_str());
  24256. Server svr;
  24257. std::mutex mtx;
  24258. std::string received_host;
  24259. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24260. {
  24261. std::lock_guard<std::mutex> lock(mtx);
  24262. received_host = req.get_header_value("Host");
  24263. }
  24264. std::string msg;
  24265. while (ws.read(msg)) {
  24266. ws.send(msg);
  24267. }
  24268. });
  24269. svr.set_address_family(AF_UNIX);
  24270. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24271. auto se = detail::scope_exit([&] {
  24272. svr.stop();
  24273. t.join();
  24274. std::remove(sock_path.c_str());
  24275. });
  24276. svr.wait_until_ready();
  24277. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24278. client.set_address_family(AF_UNIX);
  24279. ASSERT_TRUE(client.connect());
  24280. ASSERT_TRUE(client.send("hello"));
  24281. std::string msg;
  24282. ASSERT_TRUE(client.read(msg));
  24283. client.close();
  24284. {
  24285. std::lock_guard<std::mutex> lock(mtx);
  24286. // There is no host:port for a Unix socket, so the same "localhost"
  24287. // placeholder the HTTP client uses is expected.
  24288. EXPECT_EQ("localhost", received_host);
  24289. }
  24290. }
  24291. // Two threads must never parse WebSocket frames from the same stream.
  24292. // close() used to read the peer's Close reply with its own frame read, so it
  24293. // raced a reader thread that was in the middle of a payload: the payload loop
  24294. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24295. // so bytes taken by close() were replaced with bytes from further along the
  24296. // stream. The message kept its length and silently changed content.
  24297. //
  24298. // The raw peer below sends a frame header plus part of the payload, waits for
  24299. // the handler to call close(), and only then sends the rest. Whichever thread
  24300. // would win the race for those bytes, the message must arrive intact, because
  24301. // close() must not touch the stream while read() owns it.
  24302. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24303. #ifndef _WIN32
  24304. signal(SIGPIPE, SIG_IGN);
  24305. #endif
  24306. const size_t payload_len = 120; // fits the 7-bit length field
  24307. const size_t prefix_len = 8;
  24308. const int attempts = 8;
  24309. std::string expected(payload_len, '\0');
  24310. for (size_t i = 0; i < payload_len; i++) {
  24311. expected[i] = static_cast<char>('a' + i % 26);
  24312. }
  24313. std::atomic<bool> peer_stalled{false};
  24314. std::atomic<bool> handler_done{false};
  24315. std::mutex received_mutex;
  24316. std::vector<std::string> received;
  24317. // Bound every wait, so a regression fails the test instead of hanging the
  24318. // suite.
  24319. auto wait_for = [](const std::atomic<bool> &flag) {
  24320. for (int i = 0; i < 500 && !flag; i++) {
  24321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24322. }
  24323. };
  24324. Server svr;
  24325. svr.set_websocket_ping_interval(0);
  24326. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24327. std::thread reader([&]() {
  24328. std::string msg;
  24329. while (ws.read(msg)) {
  24330. std::lock_guard<std::mutex> guard(received_mutex);
  24331. received.push_back(msg);
  24332. }
  24333. });
  24334. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24335. // inside read_websocket_frame() when close() runs.
  24336. wait_for(peer_stalled);
  24337. ws.close();
  24338. reader.join();
  24339. handler_done = true;
  24340. });
  24341. auto port = svr.bind_to_any_port("127.0.0.1");
  24342. std::thread t([&]() { svr.listen_after_bind(); });
  24343. auto se = detail::scope_exit([&] {
  24344. svr.stop();
  24345. t.join();
  24346. });
  24347. svr.wait_until_ready();
  24348. auto send_bytes = [](socket_t s, const std::string &data) {
  24349. #ifdef _WIN32
  24350. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24351. #else
  24352. auto n = ::send(s, data.data(), data.size(), 0);
  24353. #endif
  24354. return n == static_cast<decltype(n)>(data.size());
  24355. };
  24356. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24357. // Every length used here fits the 7-bit length field.
  24358. auto masked_header = [](uint8_t first_byte, size_t len) {
  24359. std::string h;
  24360. h += static_cast<char>(first_byte);
  24361. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24362. h.append(4, '\0'); // mask key
  24363. return h;
  24364. };
  24365. for (int attempt = 0; attempt < attempts; attempt++) {
  24366. peer_stalled = false;
  24367. handler_done = false;
  24368. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24369. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24370. auto se_sock = detail::scope_exit([&] {
  24371. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24372. });
  24373. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24374. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24375. sockaddr_in addr{};
  24376. addr.sin_family = AF_INET;
  24377. addr.sin_port = htons(static_cast<uint16_t>(port));
  24378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24379. ASSERT_EQ(
  24380. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24381. << "attempt " << attempt;
  24382. ASSERT_TRUE(send_bytes(sock,
  24383. "GET /ws HTTP/1.1\r\n"
  24384. "Host: 127.0.0.1\r\n"
  24385. "Upgrade: websocket\r\n"
  24386. "Connection: Upgrade\r\n"
  24387. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24388. "Sec-WebSocket-Version: 13\r\n"
  24389. "\r\n"))
  24390. << "attempt " << attempt;
  24391. std::string response;
  24392. while (response.find("\r\n\r\n") == std::string::npos) {
  24393. char buf[512];
  24394. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24395. if (n <= 0) { break; }
  24396. response.append(buf, static_cast<size_t>(n));
  24397. }
  24398. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24399. << "attempt " << attempt;
  24400. // Send the header of a Binary message but only the first prefix_len bytes
  24401. // of its payload, leaving the reader thread stalled inside the payload.
  24402. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24403. expected.substr(0, prefix_len)))
  24404. << "attempt " << attempt;
  24405. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24406. peer_stalled = true;
  24407. // Let close() send its Close frame and park in its own read before the
  24408. // rest of the payload arrives, so both threads are waiting for it.
  24409. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24410. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24411. close_frame += static_cast<char>(0x03); // status 1000
  24412. close_frame += static_cast<char>(0xE8);
  24413. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24414. << "attempt " << attempt;
  24415. // Closing the peer releases the reader thread even on the buggy path,
  24416. // where it waits for bytes another thread already consumed.
  24417. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24418. detail::close_socket(sock);
  24419. sock = INVALID_SOCKET;
  24420. wait_for(handler_done);
  24421. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24422. }
  24423. std::lock_guard<std::mutex> guard(received_mutex);
  24424. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24425. << "a message in flight when close() ran was dropped";
  24426. for (size_t i = 0; i < received.size(); i++) {
  24427. EXPECT_EQ(expected, received[i]) << "message " << i;
  24428. }
  24429. }
  24430. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24431. // returning the socket, or INVALID_SOCKET.
  24432. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24433. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24434. if (sock == INVALID_SOCKET) { return sock; }
  24435. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24436. sockaddr_in addr{};
  24437. addr.sin_family = AF_INET;
  24438. addr.sin_port = htons(static_cast<uint16_t>(port));
  24439. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24440. std::string req = "GET " + path +
  24441. " HTTP/1.1\r\n"
  24442. "Host: 127.0.0.1\r\n"
  24443. "Upgrade: websocket\r\n"
  24444. "Connection: Upgrade\r\n"
  24445. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24446. "Sec-WebSocket-Version: 13\r\n"
  24447. "\r\n";
  24448. std::string res;
  24449. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24450. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24451. static_cast<ssize_t>(req.size())) {
  24452. char c;
  24453. while (res.find("\r\n\r\n") == std::string::npos &&
  24454. ::recv(sock, &c, 1, 0) == 1) {
  24455. res += c;
  24456. }
  24457. }
  24458. if (res.find(" 101 ") == std::string::npos) {
  24459. detail::close_socket(sock);
  24460. return INVALID_SOCKET;
  24461. }
  24462. return sock;
  24463. }
  24464. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24465. // The payload must fit the 7-bit length field.
  24466. static std::string masked_frame(uint8_t first_byte,
  24467. const std::string &payload) {
  24468. std::string f;
  24469. f += static_cast<char>(first_byte);
  24470. f += static_cast<char>(0x80 | payload.size());
  24471. f.append(4, '\0');
  24472. return f + payload;
  24473. }
  24474. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24475. std::atomic<bool> done{false};
  24476. std::string received;
  24477. Server svr;
  24478. svr.set_websocket_ping_interval(0);
  24479. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24480. std::string msg;
  24481. if (ws.read(msg) == ws::Binary) { received = msg; }
  24482. done = true;
  24483. });
  24484. auto port = svr.bind_to_any_port("127.0.0.1");
  24485. std::thread t([&]() { svr.listen_after_bind(); });
  24486. auto se = detail::scope_exit([&] {
  24487. svr.stop();
  24488. t.join();
  24489. });
  24490. svr.wait_until_ready();
  24491. auto sock = connect_raw_websocket(port, "/ws");
  24492. ASSERT_NE(INVALID_SOCKET, sock);
  24493. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24494. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24495. masked_frame(0x89, "p") + // FIN + Ping
  24496. masked_frame(0x80, "lo"); // FIN + Continuation
  24497. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24498. for (int i = 0; i < 500 && !done; i++) {
  24499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24500. }
  24501. ASSERT_TRUE(done);
  24502. EXPECT_EQ("Hello", received);
  24503. // The Ping between the fragments is answered with a Pong.
  24504. char pong[3];
  24505. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24506. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24507. }
  24508. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24509. Server svr;
  24510. svr.set_websocket_ping_interval(-1);
  24511. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24512. std::string msg;
  24513. while (ws.read(msg)) {}
  24514. });
  24515. auto port = svr.bind_to_any_port("127.0.0.1");
  24516. std::thread t([&]() { svr.listen_after_bind(); });
  24517. auto se = detail::scope_exit([&] {
  24518. svr.stop();
  24519. t.join();
  24520. });
  24521. svr.wait_until_ready();
  24522. auto sock = connect_raw_websocket(port, "/ws");
  24523. ASSERT_NE(INVALID_SOCKET, sock);
  24524. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24525. // Nothing comes while the client stays quiet.
  24526. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24527. char c;
  24528. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24529. }
  24530. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24531. // and that has to end a read() already waiting on the peer, on every platform.
  24532. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24533. // The peer sends no pings, and its handler never calls read(), which is
  24534. // where pongs are written.
  24535. std::mutex mutex;
  24536. std::condition_variable cv;
  24537. auto release = false;
  24538. svr.set_websocket_ping_interval(0);
  24539. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24540. std::unique_lock<std::mutex> lock(mutex);
  24541. cv.wait(lock, [&] { return release; });
  24542. });
  24543. auto port = svr.bind_to_any_port(HOST);
  24544. std::thread t([&]() { svr.listen_after_bind(); });
  24545. auto se = detail::scope_exit([&] {
  24546. {
  24547. std::lock_guard<std::mutex> lock(mutex);
  24548. release = true;
  24549. }
  24550. cv.notify_all();
  24551. svr.stop();
  24552. t.join();
  24553. });
  24554. svr.wait_until_ready();
  24555. ws::WebSocketClient client(std::string(scheme) +
  24556. "://localhost:" + std::to_string(port) + "/ws");
  24557. #ifdef CPPHTTPLIB_SSL_ENABLED
  24558. client.enable_server_certificate_verification(false);
  24559. #endif
  24560. // A ping a second, given up on after two go unanswered: about 3s
  24561. client.set_websocket_ping_interval(1);
  24562. client.set_websocket_max_missed_pongs(2);
  24563. // Well past that, so that a read the timeout ends instead stands out
  24564. client.set_read_timeout(10);
  24565. ASSERT_TRUE(client.connect());
  24566. auto start = std::chrono::steady_clock::now();
  24567. std::string msg;
  24568. EXPECT_EQ(ws::Fail, client.read(msg));
  24569. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24570. std::chrono::steady_clock::now() - start)
  24571. .count(),
  24572. 6000);
  24573. EXPECT_FALSE(client.is_open());
  24574. }
  24575. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24576. Server svr;
  24577. check_pong_timeout_ends_read(svr, "ws");
  24578. }
  24579. #ifdef CPPHTTPLIB_SSL_ENABLED
  24580. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24582. ASSERT_TRUE(svr.is_valid());
  24583. check_pong_timeout_ends_read(svr, "wss");
  24584. }
  24585. #endif
  24586. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24587. Server svr;
  24588. svr.set_websocket_ping_interval(0);
  24589. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24590. std::string msg;
  24591. while (ws.read(msg)) {}
  24592. });
  24593. auto port = svr.bind_to_any_port("127.0.0.1");
  24594. std::thread t([&]() { svr.listen_after_bind(); });
  24595. auto se = detail::scope_exit([&] {
  24596. svr.stop();
  24597. t.join();
  24598. });
  24599. svr.wait_until_ready();
  24600. // Each Close payload and the reply it should get: an echo when valid, 1002
  24601. // otherwise.
  24602. std::vector<std::pair<std::string, std::string>> cases = {
  24603. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24604. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24605. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24606. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24607. };
  24608. // Also between the fragments of a message.
  24609. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24610. for (const auto &c : cases) {
  24611. auto sock = connect_raw_websocket(port, "/ws");
  24612. ASSERT_NE(INVALID_SOCKET, sock);
  24613. auto frames = prefix + masked_frame(0x88, c.first);
  24614. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24615. std::string reply;
  24616. char buf[256];
  24617. while (reply.size() < 2 + c.second.size()) {
  24618. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24619. if (n <= 0) { break; }
  24620. reply.append(buf, static_cast<size_t>(n));
  24621. }
  24622. detail::close_socket(sock);
  24623. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24624. c.second,
  24625. reply);
  24626. }
  24627. }
  24628. }
  24629. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24630. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24631. protected:
  24632. void SetUp() override {
  24633. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24634. SERVER_PRIVATE_KEY_FILE);
  24635. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24636. std::string msg;
  24637. ws::ReadResult ret;
  24638. while ((ret = ws.read(msg))) {
  24639. if (ret == ws::Binary) {
  24640. ws.send(msg.data(), msg.size());
  24641. } else {
  24642. ws.send(msg);
  24643. }
  24644. }
  24645. });
  24646. port_ = server_->bind_to_any_port(HOST);
  24647. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24648. server_->wait_until_ready();
  24649. }
  24650. void TearDown() override {
  24651. server_->stop();
  24652. if (server_thread_.joinable()) { server_thread_.join(); }
  24653. }
  24654. std::unique_ptr<SSLServer> server_;
  24655. std::thread server_thread_;
  24656. int port_ = 0;
  24657. };
  24658. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24659. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24660. {
  24661. ws::WebSocketClient client(url);
  24662. client.enable_server_certificate_verification(false);
  24663. auto calls = 0;
  24664. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24665. calls++;
  24666. return false;
  24667. });
  24668. EXPECT_FALSE(client.connect());
  24669. EXPECT_GT(calls, 0);
  24670. }
  24671. {
  24672. ws::WebSocketClient client(url);
  24673. client.enable_server_certificate_verification(false);
  24674. client.set_session_verifier([](tls::session_t) {
  24675. return SSLVerifierResponse::CertificateRejected;
  24676. });
  24677. EXPECT_FALSE(client.connect());
  24678. }
  24679. {
  24680. ws::WebSocketClient client(url);
  24681. client.enable_server_certificate_verification(false);
  24682. client.set_session_verifier([](tls::session_t) {
  24683. return SSLVerifierResponse::CertificateAccepted;
  24684. });
  24685. EXPECT_TRUE(client.connect());
  24686. }
  24687. }
  24688. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24689. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24690. "/ws-echo");
  24691. client.enable_server_certificate_verification(false);
  24692. ASSERT_TRUE(client.connect());
  24693. ASSERT_TRUE(client.is_open());
  24694. ASSERT_TRUE(client.send("Hello WSS"));
  24695. std::string msg;
  24696. EXPECT_EQ(ws::Text, client.read(msg));
  24697. EXPECT_EQ("Hello WSS", msg);
  24698. client.close();
  24699. }
  24700. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24701. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24702. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24703. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24704. // client (without calling close() first) is the only path that runs
  24705. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24706. // bug exactly.
  24707. //
  24708. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24709. // when linked against an instrumented libssl; run under Valgrind to catch it
  24710. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24711. // suite (the freed session otherwise stalls on the close handshake) — this test
  24712. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24713. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24714. {
  24715. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24716. "/ws-echo");
  24717. client.enable_server_certificate_verification(false);
  24718. client.set_read_timeout(2, 0);
  24719. client.set_write_timeout(2, 0);
  24720. ASSERT_TRUE(client.connect());
  24721. ASSERT_TRUE(client.is_open());
  24722. ASSERT_TRUE(client.send("still open"));
  24723. // Intentionally do NOT call client.close(): leaving scope runs
  24724. // shutdown_and_close() with the WebSocket still open, which must send the
  24725. // close frame while the TLS session is still alive.
  24726. }
  24727. }
  24728. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24729. // shutdown_and_close() at the start of connect(), reproducing the same
  24730. // use-after-free within the test body rather than at scope exit. The second
  24731. // connect must succeed and echo, proving the close handshake ran over a live
  24732. // session. See the note above about memory-tool requirements.
  24733. TEST_F(WebSocketSSLIntegrationTest,
  24734. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24735. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24736. "/ws-echo");
  24737. client.enable_server_certificate_verification(false);
  24738. client.set_read_timeout(2, 0);
  24739. client.set_write_timeout(2, 0);
  24740. ASSERT_TRUE(client.connect());
  24741. ASSERT_TRUE(client.is_open());
  24742. ASSERT_TRUE(client.send("still open"));
  24743. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24744. // the still-open connection, which must not touch a freed TLS session.
  24745. ASSERT_TRUE(client.connect());
  24746. ASSERT_TRUE(client.is_open());
  24747. ASSERT_TRUE(client.send("after reconnect"));
  24748. std::string msg;
  24749. EXPECT_EQ(ws::Text, client.read(msg));
  24750. EXPECT_EQ("after reconnect", msg);
  24751. client.close();
  24752. }
  24753. #endif
  24754. #ifdef CPPHTTPLIB_SSL_ENABLED
  24755. class WebSocketSSLCATest : public ::testing::Test {
  24756. protected:
  24757. void SetUp() override {
  24758. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24759. SERVER_PRIVATE_KEY_FILE);
  24760. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24761. std::string msg;
  24762. while (ws.read(msg)) {
  24763. ws.send(msg);
  24764. }
  24765. });
  24766. port_ = server_->bind_to_any_port("127.0.0.1");
  24767. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24768. server_->wait_until_ready();
  24769. }
  24770. void TearDown() override {
  24771. server_->stop();
  24772. if (server_thread_.joinable()) { server_thread_.join(); }
  24773. }
  24774. std::string url() const {
  24775. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24776. }
  24777. std::unique_ptr<SSLServer> server_;
  24778. std::thread server_thread_;
  24779. int port_ = 0;
  24780. };
  24781. // A custom CA loaded as PEM verifies the server with full certificate
  24782. // verification enabled
  24783. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24784. ws::WebSocketClient client(url());
  24785. std::string cert;
  24786. read_file(SERVER_CERT2_FILE, cert);
  24787. client.load_ca_cert_store(cert.c_str(), cert.size());
  24788. ASSERT_TRUE(client.connect());
  24789. ASSERT_TRUE(client.send("hello"));
  24790. std::string msg;
  24791. EXPECT_EQ(ws::Text, client.read(msg));
  24792. EXPECT_EQ("hello", msg);
  24793. client.close();
  24794. }
  24795. // A custom CA that does not cover the server must fail verification (the
  24796. // custom CA is exclusive; system certs are not loaded alongside it)
  24797. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24798. ws::WebSocketClient client(url());
  24799. std::string cert;
  24800. read_file(CLIENT_CA_CERT_FILE, cert);
  24801. client.load_ca_cert_store(cert.c_str(), cert.size());
  24802. auto res = client.connect();
  24803. ASSERT_FALSE(res);
  24804. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24805. EXPECT_EQ(-1, res.status());
  24806. EXPECT_NE(0u, res.ssl_backend_error());
  24807. }
  24808. // The same CA as a file path rather than PEM in memory
  24809. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24810. ws::WebSocketClient client(url());
  24811. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24812. ASSERT_TRUE(client.connect());
  24813. ASSERT_TRUE(client.send("hello"));
  24814. std::string msg;
  24815. EXPECT_EQ(ws::Text, client.read(msg));
  24816. EXPECT_EQ("hello", msg);
  24817. client.close();
  24818. }
  24819. // ...and a CA file that does not cover the server still fails, so it is the
  24820. // path above that decides the outcome
  24821. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24822. ws::WebSocketClient client(url());
  24823. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24824. ASSERT_FALSE(client.connect());
  24825. }
  24826. // Regression test: reconnecting with a native custom CA store used to reuse
  24827. // a store handle the previous TLS context had already freed (use-after-free
  24828. // under the OpenSSL backend). The context now lives as long as the client.
  24829. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24830. ws::WebSocketClient client(url());
  24831. std::string cert;
  24832. read_file(SERVER_CERT2_FILE, cert);
  24833. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24834. ASSERT_TRUE(client.connect());
  24835. client.close();
  24836. ASSERT_TRUE(client.connect());
  24837. ASSERT_TRUE(client.send("again"));
  24838. std::string msg;
  24839. EXPECT_EQ(ws::Text, client.read(msg));
  24840. EXPECT_EQ("again", msg);
  24841. client.close();
  24842. }
  24843. // Regression test: a certificate with a trusted chain but no identity match
  24844. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24845. // verification entirely for IP hosts, so this connection succeeded there.
  24846. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24847. // chain verification while the identity check must still fail.
  24848. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24850. ASSERT_TRUE(svr.is_valid());
  24851. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24852. std::string msg;
  24853. while (ws.read(msg)) {
  24854. ws.send(msg);
  24855. }
  24856. });
  24857. auto port = svr.bind_to_any_port("127.0.0.1");
  24858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24859. auto se = detail::scope_exit([&] {
  24860. svr.stop();
  24861. t.join();
  24862. });
  24863. svr.wait_until_ready();
  24864. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24865. "/echo");
  24866. std::string cert;
  24867. read_file(SERVER_CERT_FILE, cert);
  24868. client.load_ca_cert_store(cert.c_str(), cert.size());
  24869. ASSERT_FALSE(client.connect());
  24870. }
  24871. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24872. // SNI, so nothing binds the host name to the TLS session. These bind the
  24873. // server to "localhost" instead, the only shape that exercises the SNI and
  24874. // hostname-verification path with certificate verification left enabled.
  24875. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24876. protected:
  24877. void Start(const char *cert_file) {
  24878. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24879. SERVER_PRIVATE_KEY_FILE);
  24880. ASSERT_TRUE(server_->is_valid());
  24881. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24882. std::string msg;
  24883. while (ws.read(msg)) {
  24884. ws.send(msg);
  24885. }
  24886. });
  24887. port_ = server_->bind_to_any_port("localhost");
  24888. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24889. server_->wait_until_ready();
  24890. }
  24891. void TearDown() override {
  24892. if (server_) { server_->stop(); }
  24893. if (server_thread_.joinable()) { server_thread_.join(); }
  24894. }
  24895. std::string url() const {
  24896. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24897. }
  24898. std::unique_ptr<SSLServer> server_;
  24899. std::thread server_thread_;
  24900. int port_ = 0;
  24901. };
  24902. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24903. // out and the connection is usable
  24904. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24905. Start(SERVER_CERT2_FILE);
  24906. ws::WebSocketClient client(url());
  24907. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24908. ASSERT_TRUE(client.connect());
  24909. ASSERT_TRUE(client.send("hello"));
  24910. std::string msg;
  24911. EXPECT_EQ(ws::Text, client.read(msg));
  24912. EXPECT_EQ("hello", msg);
  24913. client.close();
  24914. }
  24915. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24916. // while the identity check must still reject "localhost"
  24917. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24918. Start(SERVER_CERT_FILE);
  24919. ws::WebSocketClient client(url());
  24920. client.set_ca_cert_path(SERVER_CERT_FILE);
  24921. auto res = client.connect();
  24922. ASSERT_FALSE(res);
  24923. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24924. EXPECT_EQ(-1, res.status());
  24925. }
  24926. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24927. // disabled: the chain is still checked, only the identity check is skipped
  24928. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24929. Start(SERVER_CERT_FILE);
  24930. ws::WebSocketClient client(url());
  24931. client.set_ca_cert_path(SERVER_CERT_FILE);
  24932. client.enable_server_hostname_verification(false);
  24933. ASSERT_TRUE(client.connect());
  24934. ASSERT_TRUE(client.send("hello"));
  24935. std::string msg;
  24936. EXPECT_EQ(ws::Text, client.read(msg));
  24937. EXPECT_EQ("hello", msg);
  24938. client.close();
  24939. }
  24940. // A CA that did not sign the server certificate fails the chain, even though
  24941. // the name would match
  24942. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24943. Start(SERVER_CERT2_FILE);
  24944. ws::WebSocketClient client(url());
  24945. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24946. ASSERT_FALSE(client.connect());
  24947. }
  24948. // With verification disabled, neither the chain nor the name is checked
  24949. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24950. Start(SERVER_CERT_FILE);
  24951. ws::WebSocketClient client(url());
  24952. client.enable_server_certificate_verification(false);
  24953. ASSERT_TRUE(client.connect());
  24954. ASSERT_TRUE(client.send("hello"));
  24955. std::string msg;
  24956. EXPECT_EQ(ws::Text, client.read(msg));
  24957. EXPECT_EQ("hello", msg);
  24958. client.close();
  24959. }
  24960. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24961. protected:
  24962. void SetUp() override {
  24963. server_ = httplib::detail::make_unique<SSLServer>(
  24964. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24965. ASSERT_TRUE(server_->is_valid());
  24966. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24967. std::string msg;
  24968. while (ws.read(msg)) {
  24969. ws.send(msg);
  24970. }
  24971. });
  24972. port_ = server_->bind_to_any_port("localhost");
  24973. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24974. server_->wait_until_ready();
  24975. }
  24976. void TearDown() override {
  24977. server_->stop();
  24978. if (server_thread_.joinable()) { server_thread_.join(); }
  24979. }
  24980. std::string url() const {
  24981. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24982. }
  24983. void ConnectWithClientCert(const std::string &client_cert_file,
  24984. const std::string &client_private_key_file,
  24985. const char *private_key_password) {
  24986. std::string cert_pem, key_pem;
  24987. read_file(client_cert_file, cert_pem);
  24988. read_file(client_private_key_file, key_pem);
  24989. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24990. key_pem.c_str(), key_pem.size(),
  24991. private_key_password};
  24992. ConnectWithPem(pem);
  24993. }
  24994. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24995. ws::WebSocketClient client(url(), pem);
  24996. ASSERT_TRUE(client.is_valid());
  24997. client.enable_server_certificate_verification(false);
  24998. ASSERT_TRUE(client.connect());
  24999. ASSERT_TRUE(client.send("hello"));
  25000. std::string msg;
  25001. EXPECT_EQ(ws::Text, client.read(msg));
  25002. EXPECT_EQ("hello", msg);
  25003. client.close();
  25004. }
  25005. std::unique_ptr<SSLServer> server_;
  25006. std::thread server_thread_;
  25007. int port_ = 0;
  25008. };
  25009. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25010. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25011. }
  25012. // Control for the tests above: the fixture's server really does require a
  25013. // client certificate, so it is the PEM the constructor installed that decides
  25014. // the outcome.
  25015. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25016. ws::WebSocketClient client(url());
  25017. ASSERT_TRUE(client.is_valid());
  25018. client.enable_server_certificate_verification(false);
  25019. EXPECT_FALSE(client.connect());
  25020. }
  25021. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25022. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25023. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25024. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25025. }
  25026. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25027. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25028. std::string cert_pem, key_pem;
  25029. read_file(CLIENT_CERT_FILE, cert_pem);
  25030. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25031. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25032. std::vector<char> key(key_pem.begin(), key_pem.end());
  25033. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25034. key.size(), nullptr};
  25035. ConnectWithPem(pem);
  25036. }
  25037. #endif
  25038. #if !defined(_WIN32)
  25039. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25040. auto secret_dir = std::string("./symlink_test_secret");
  25041. auto served_dir = std::string("./symlink_test_served");
  25042. auto secret_file = secret_dir + "/secret.txt";
  25043. auto symlink_path = served_dir + "/escape";
  25044. // Setup: create directories and files
  25045. mkdir(secret_dir.c_str(), 0755);
  25046. mkdir(served_dir.c_str(), 0755);
  25047. {
  25048. std::ofstream ofs(secret_file);
  25049. ofs << "SECRET_DATA";
  25050. }
  25051. // Create symlink using absolute path so it resolves correctly
  25052. #ifdef PATH_MAX
  25053. char abs_secret[PATH_MAX];
  25054. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25055. #else
  25056. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25057. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25058. ASSERT_NE(nullptr, abs_secret);
  25059. #endif
  25060. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25061. auto se = detail::scope_exit([&] {
  25062. unlink(symlink_path.c_str());
  25063. unlink(secret_file.c_str());
  25064. rmdir(served_dir.c_str());
  25065. rmdir(secret_dir.c_str());
  25066. });
  25067. Server svr;
  25068. svr.set_mount_point("/", served_dir);
  25069. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25070. auto se2 = detail::scope_exit([&] {
  25071. svr.stop();
  25072. listen_thread.join();
  25073. });
  25074. svr.wait_until_ready();
  25075. Client cli("localhost", PORT);
  25076. // Symlink pointing outside base dir should be blocked
  25077. auto res = cli.Get("/escape/secret.txt");
  25078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25079. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25080. }
  25081. #endif
  25082. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25083. // "GET /smuggled" request), reads the first response, and only then sends the
  25084. // embedded request as the body. Returns how many times /smuggled ran.
  25085. //
  25086. // The body is sent AFTER receiving the first response (as in the original
  25087. // PoC) so that the stream_line_reader cannot buffer it together with the
  25088. // headers of the first request.
  25089. static int count_smuggled_requests(const std::string &outer_head,
  25090. std::string &first_response) {
  25091. Server svr;
  25092. svr.set_mount_point("/", "./www");
  25093. std::atomic<int> smuggled_count(0);
  25094. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25095. smuggled_count++;
  25096. res.set_content("oops", "text/plain");
  25097. });
  25098. svr.Post("/post", [&](const Request &req, Response &res) {
  25099. res.set_content(req.body, "text/plain");
  25100. });
  25101. auto port = svr.bind_to_any_port("localhost");
  25102. thread t = thread([&] { svr.listen_after_bind(); });
  25103. auto se = detail::scope_exit([&] {
  25104. svr.stop();
  25105. t.join();
  25106. });
  25107. svr.wait_until_ready();
  25108. auto error = Error::Success;
  25109. auto sock = detail::create_client_socket(
  25110. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25111. /*connection_timeout_sec=*/2, 0,
  25112. /*read_timeout_sec=*/2, 0,
  25113. /*write_timeout_sec=*/2, 0, std::string(), error);
  25114. EXPECT_NE(INVALID_SOCKET, sock);
  25115. if (sock == INVALID_SOCKET) { return -1; }
  25116. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25117. // The "smuggled" request will be sent as the body of the outer request
  25118. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25119. "Host: localhost\r\n"
  25120. "Connection: close\r\n"
  25121. "\r\n";
  25122. auto head = outer_head;
  25123. auto len = std::to_string(smuggled.size());
  25124. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25125. pos = head.find("{len}", pos + len.size())) {
  25126. head.replace(pos, 5, len);
  25127. }
  25128. // Step 1: Send only the outer request headers (no body yet)
  25129. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25130. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25131. // Step 2: Read the first response
  25132. char buf[4096];
  25133. for (;;) {
  25134. auto n = recv(sock, buf, sizeof(buf), 0);
  25135. if (n <= 0) break;
  25136. first_response.append(buf, static_cast<size_t>(n));
  25137. // Stop once we have a complete response (headers + body)
  25138. auto hdr_end = first_response.find("\r\n\r\n");
  25139. if (hdr_end != std::string::npos) {
  25140. // Check for Content-Length to know when the body is complete
  25141. auto cl_pos = first_response.find("Content-Length:");
  25142. if (cl_pos != std::string::npos) {
  25143. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25144. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25145. auto cl = std::stoul(
  25146. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25147. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25148. } else {
  25149. break; // No Content-Length, assume headers-only response
  25150. }
  25151. }
  25152. }
  25153. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25154. // vulnerable server the keep-alive loop reads this as a second request. The
  25155. // server may already have closed the connection, so the result is ignored.
  25156. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25157. // Half-close so that a server which drained the body sees EOF and closes,
  25158. // instead of the read below waiting for the read timeout.
  25159. #ifdef _WIN32
  25160. ::shutdown(sock, SD_SEND);
  25161. #else
  25162. ::shutdown(sock, SHUT_WR);
  25163. #endif
  25164. // Step 4: Read until the server closes the connection
  25165. for (;;) {
  25166. auto n = recv(sock, buf, sizeof(buf), 0);
  25167. if (n <= 0) break;
  25168. }
  25169. return smuggled_count.load();
  25170. }
  25171. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25172. // A GET request with Content-Length to a static file handler must have its
  25173. // body drained before the keep-alive connection is reused. Otherwise the
  25174. // unread body bytes are interpreted as the next HTTP request.
  25175. std::string first_response;
  25176. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25177. "Host: localhost\r\n"
  25178. "Content-Length: {len}\r\n"
  25179. "\r\n",
  25180. first_response));
  25181. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25182. }
  25183. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25184. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25185. // be answered with 400 and the connection closed. Treating it as "no body"
  25186. // leaves the body to be parsed as the next request.
  25187. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25188. const char *targets[] = {
  25189. "GET /file", // handler that never reads the body
  25190. "GET /not-found", // no handler matches (404)
  25191. "POST /post", // handler that reads the body
  25192. };
  25193. for (auto target : targets) {
  25194. for (auto value : values) {
  25195. std::string first_response;
  25196. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25197. " HTTP/1.1\r\n"
  25198. "Host: localhost\r\n"
  25199. "Content-Length: " +
  25200. value + "\r\n\r\n",
  25201. first_response))
  25202. << target << " with Content-Length: " << value;
  25203. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25204. << target << " with Content-Length: " << value;
  25205. }
  25206. }
  25207. }
  25208. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25209. // A 400 for an unparseable request line leaves the rest of the message
  25210. // unread, so the connection must be closed rather than reused.
  25211. std::string first_response;
  25212. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25213. "Host: localhost\r\n"
  25214. "Content-Length: {len}\r\n"
  25215. "\r\n",
  25216. first_response));
  25217. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25218. }
  25219. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25220. // Same as above for a header block that fails to parse.
  25221. std::string first_response;
  25222. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25223. "Host: localhost\r\n"
  25224. "Bad Header\r\n"
  25225. "Content-Length: {len}\r\n"
  25226. "\r\n",
  25227. first_response));
  25228. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25229. }
  25230. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25231. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25232. // server must not read another request on that connection, even when the
  25233. // request had no body to drain.
  25234. std::string first_response;
  25235. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25236. "Host: localhost\r\n"
  25237. "\r\n",
  25238. first_response));
  25239. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25240. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25241. }
  25242. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25243. // A content reader that stops early leaves the stream inside the body.
  25244. // Draining the whole Content-Length from there, or reading the body again,
  25245. // reads into the next request, and whatever follows is parsed as a request
  25246. // of its own.
  25247. Server svr;
  25248. std::atomic<int> smuggled_count(0);
  25249. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25250. svr.Post("/upload", [](const Request &req, Response &res,
  25251. const ContentReader &content_reader) {
  25252. // Stop at the last chunk, so the whole body has been read however it
  25253. // arrives.
  25254. auto length = req.get_header_value_u64("Content-Length");
  25255. size_t total = 0;
  25256. auto consumed = content_reader([&](const char *, size_t n) {
  25257. total += n;
  25258. return total < length;
  25259. });
  25260. EXPECT_FALSE(consumed);
  25261. if (req.has_param("retry")) {
  25262. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25263. }
  25264. // Replace the 400 the aborted read set, which would close the connection.
  25265. res.set_redirect("/done");
  25266. });
  25267. auto port = svr.bind_to_any_port(HOST);
  25268. thread t = thread([&] { svr.listen_after_bind(); });
  25269. auto se = detail::scope_exit([&] {
  25270. svr.stop();
  25271. t.join();
  25272. });
  25273. svr.wait_until_ready();
  25274. // A front end sees the second request as a POST whose body is the GET. The
  25275. // first body is as long as the POST's headers, so draining it again reads
  25276. // exactly those and leaves the GET to be parsed next.
  25277. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25278. "Host: localhost\r\n"
  25279. "\r\n";
  25280. std::string second_head = "POST /post HTTP/1.1\r\n"
  25281. "Host: localhost\r\n"
  25282. "Content-Length: " +
  25283. std::to_string(inner.size()) +
  25284. "\r\n"
  25285. "\r\n";
  25286. for (auto target : {"/upload", "/upload?retry"}) {
  25287. smuggled_count = 0;
  25288. std::string request = "POST " + std::string(target) +
  25289. " HTTP/1.1\r\n"
  25290. "Host: localhost\r\n"
  25291. "Content-Length: " +
  25292. std::to_string(second_head.size()) +
  25293. "\r\n"
  25294. "\r\n" +
  25295. std::string(second_head.size(), 'A') + second_head +
  25296. inner;
  25297. std::string response;
  25298. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25299. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25300. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25301. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25302. EXPECT_EQ(0, smuggled_count.load()) << target;
  25303. }
  25304. }
  25305. // An error response closes the connection anyway, so the body is left unread
  25306. // with a redirect, such as one to a login page.
  25307. static void serve_redirects(Server &svr,
  25308. const std::function<void(int)> &client) {
  25309. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25310. res.set_redirect("/login");
  25311. return Server::HandlerResponse::Handled;
  25312. });
  25313. auto port = svr.bind_to_any_port(HOST);
  25314. ASSERT_GT(port, 0);
  25315. thread t = thread([&] { svr.listen_after_bind(); });
  25316. auto se = detail::scope_exit([&] {
  25317. svr.stop();
  25318. t.join();
  25319. ASSERT_FALSE(svr.is_running());
  25320. });
  25321. svr.wait_until_ready();
  25322. client(port);
  25323. }
  25324. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25325. Server svr;
  25326. serve_redirects(svr, [](int port) {
  25327. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25328. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25329. std::to_string(body.size()) + "\r\n\r\n" + body +
  25330. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25331. std::string resp;
  25332. ASSERT_TRUE(send_request(1, req, &resp, port));
  25333. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25334. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25335. });
  25336. }
  25337. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25338. Server svr;
  25339. svr.set_read_timeout(0, 200000);
  25340. serve_redirects(svr, [](int port) {
  25341. // A byte every 100 ms keeps each read within the read timeout, but not the
  25342. // body as a whole, so the server closes and the bytes sent after that fail.
  25343. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25344. "Content-Length: 10\r\n\r\n"};
  25345. parts.resize(11, "x");
  25346. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25347. });
  25348. }
  25349. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25350. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25351. // must be rejected with 400 Bad Request.
  25352. Server svr;
  25353. svr.Post("/test", [&](const Request &, Response &res) {
  25354. res.set_content("ok", "text/plain");
  25355. });
  25356. thread t = thread([&] { svr.listen(HOST, PORT); });
  25357. auto se = detail::scope_exit([&] {
  25358. svr.stop();
  25359. t.join();
  25360. ASSERT_FALSE(svr.is_running());
  25361. });
  25362. svr.wait_until_ready();
  25363. // Exact "chunked"
  25364. {
  25365. auto req = "POST /test HTTP/1.1\r\n"
  25366. "Host: localhost\r\n"
  25367. "Content-Length: 5\r\n"
  25368. "Transfer-Encoding: chunked\r\n"
  25369. "Connection: close\r\n"
  25370. "\r\n"
  25371. "hello";
  25372. std::string response;
  25373. ASSERT_TRUE(send_request(1, req, &response));
  25374. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25375. response.substr(0, response.find("\r\n")));
  25376. }
  25377. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25378. {
  25379. auto req = "POST /test HTTP/1.1\r\n"
  25380. "Host: localhost\r\n"
  25381. "Content-Length: 5\r\n"
  25382. "Transfer-Encoding: gzip, chunked\r\n"
  25383. "Connection: close\r\n"
  25384. "\r\n"
  25385. "hello";
  25386. std::string response;
  25387. ASSERT_TRUE(send_request(1, req, &response));
  25388. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25389. response.substr(0, response.find("\r\n")));
  25390. }
  25391. }
  25392. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25393. Server svr;
  25394. svr.Post("/test", [&](const Request &, Response &res) {
  25395. res.set_content("ok", "text/plain");
  25396. });
  25397. thread t = thread([&] { svr.listen(HOST, PORT); });
  25398. auto se = detail::scope_exit([&] {
  25399. svr.stop();
  25400. t.join();
  25401. ASSERT_FALSE(svr.is_running());
  25402. });
  25403. svr.wait_until_ready();
  25404. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25405. // length cannot be determined, so the server must answer 400 and close
  25406. // rather than treat the request as bodyless and leave the body in the
  25407. // socket for the next request to pick up.
  25408. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25409. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25410. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25411. std::string response;
  25412. ASSERT_TRUE(send_request(1, req, &response));
  25413. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25414. response.substr(0, response.find("\r\n")))
  25415. << transfer_encoding;
  25416. }
  25417. // RFC 9110 5.3: the codings may also be split across several
  25418. // Transfer-Encoding lines, which combine in the order they were received.
  25419. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25420. // just like the single-line "chunked, gzip" above.
  25421. {
  25422. auto req = "POST /test HTTP/1.1\r\n"
  25423. "Host: localhost\r\n"
  25424. "Transfer-Encoding: chunked\r\n"
  25425. "Transfer-Encoding: gzip\r\n"
  25426. "\r\n"
  25427. "0\r\n\r\n";
  25428. std::string response;
  25429. ASSERT_TRUE(send_request(1, req, &response));
  25430. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25431. response.substr(0, response.find("\r\n")));
  25432. }
  25433. }
  25434. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25435. Server svr;
  25436. svr.Post("/test", [&](const Request &, Response &res) {
  25437. res.set_content("ok", "text/plain");
  25438. });
  25439. auto port = svr.bind_to_any_port(HOST);
  25440. ASSERT_GT(port, 0);
  25441. thread t = thread([&] { svr.listen_after_bind(); });
  25442. auto se = detail::scope_exit([&] {
  25443. svr.stop();
  25444. t.join();
  25445. ASSERT_FALSE(svr.is_running());
  25446. });
  25447. svr.wait_until_ready();
  25448. for (auto transfer_encoding :
  25449. {"Transfer-Encoding: gzip, chunked\r\n",
  25450. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25451. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25452. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25453. transfer_encoding + "\r\n0\r\n\r\n";
  25454. std::string response;
  25455. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25456. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25457. response.substr(0, response.find("\r\n")))
  25458. << transfer_encoding;
  25459. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25460. << transfer_encoding;
  25461. }
  25462. }
  25463. // Regression for issue #2450: a DELETE without Content-Length on a
  25464. // keep-alive connection must not let the post-response drain consume the
  25465. // next request's bytes.
  25466. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25467. Server svr;
  25468. std::atomic<int> delete_count(0);
  25469. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25470. delete_count++;
  25471. res.status = StatusCode::NoContent_204;
  25472. });
  25473. auto port = svr.bind_to_any_port(HOST);
  25474. thread t = thread([&] { svr.listen_after_bind(); });
  25475. auto se = detail::scope_exit([&] {
  25476. svr.stop();
  25477. t.join();
  25478. });
  25479. svr.wait_until_ready();
  25480. auto error = Error::Success;
  25481. auto sock = detail::create_client_socket(
  25482. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25483. /*connection_timeout_sec=*/2, 0,
  25484. /*read_timeout_sec=*/2, 0,
  25485. /*write_timeout_sec=*/2, 0, std::string(), error);
  25486. ASSERT_NE(INVALID_SOCKET, sock);
  25487. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25488. auto send_request_and_read_response = [&](const std::string &req,
  25489. std::string &out) -> bool {
  25490. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25491. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25492. char buf[4096];
  25493. for (;;) {
  25494. auto n = recv(sock, buf, sizeof(buf), 0);
  25495. if (n <= 0) { return !out.empty(); }
  25496. out.append(buf, static_cast<size_t>(n));
  25497. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25498. }
  25499. };
  25500. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25501. "Host: localhost\r\n"
  25502. "\r\n";
  25503. std::string resp1;
  25504. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25505. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25506. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25507. "Host: localhost\r\n"
  25508. "Connection: close\r\n"
  25509. "\r\n";
  25510. std::string resp2;
  25511. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25512. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25513. EXPECT_EQ(2, delete_count.load());
  25514. }
  25515. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25516. Server svr;
  25517. svr.Post("/ingest", [&](const Request &, Response &res,
  25518. const ContentReader &content_reader) {
  25519. auto consumed = content_reader([](const char *, size_t) { return false; });
  25520. EXPECT_FALSE(consumed);
  25521. res.status = StatusCode::Conflict_409;
  25522. res.set_header("Connection", "close");
  25523. });
  25524. auto port = svr.bind_to_any_port(HOST);
  25525. thread t = thread([&] { svr.listen_after_bind(); });
  25526. auto se = detail::scope_exit([&] {
  25527. svr.stop();
  25528. t.join();
  25529. });
  25530. svr.wait_until_ready();
  25531. auto error = Error::Success;
  25532. auto sock = detail::create_client_socket(
  25533. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25534. /*connection_timeout_sec=*/2, 0,
  25535. /*read_timeout_sec=*/1, 0,
  25536. /*write_timeout_sec=*/2, 0, std::string(), error);
  25537. ASSERT_NE(INVALID_SOCKET, sock);
  25538. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25539. std::string request = "POST /ingest HTTP/1.1\r\n"
  25540. "Host: localhost\r\n"
  25541. "Transfer-Encoding: chunked\r\n"
  25542. "\r\n"
  25543. "4\r\n"
  25544. "data\r\n";
  25545. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25546. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25547. std::string response;
  25548. ssize_t received = 0;
  25549. do {
  25550. char buf[4096];
  25551. received = recv(sock, buf, sizeof(buf), 0);
  25552. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25553. } while (received > 0);
  25554. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25555. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25556. EXPECT_EQ(0, received);
  25557. }
  25558. namespace no_proxy_test {
  25559. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25560. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25561. // calling listen().
  25562. class ScopedServer {
  25563. public:
  25564. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25565. ~ScopedServer() {
  25566. svr_.stop();
  25567. if (th_.joinable()) { th_.join(); }
  25568. }
  25569. Server &svr() { return svr_; }
  25570. int port() const { return port_; }
  25571. void listen() {
  25572. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25573. svr_.wait_until_ready();
  25574. }
  25575. private:
  25576. Server svr_;
  25577. std::thread th_;
  25578. int port_ = 0;
  25579. };
  25580. class ProxyAndTargetServers {
  25581. public:
  25582. ProxyAndTargetServers() {
  25583. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25584. proxy_hits_++;
  25585. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25586. res.set_content("via-proxy", "text/plain");
  25587. });
  25588. target_.Get(".*", [this](const Request &req, Response &res) {
  25589. target_hits_++;
  25590. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25591. res.set_content("direct", "text/plain");
  25592. });
  25593. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25594. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25595. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25596. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25597. proxy_mock_.wait_until_ready();
  25598. target_.wait_until_ready();
  25599. }
  25600. ~ProxyAndTargetServers() {
  25601. proxy_mock_.stop();
  25602. target_.stop();
  25603. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25604. if (target_thread_.joinable()) { target_thread_.join(); }
  25605. }
  25606. Server &proxy_mock() { return proxy_mock_; }
  25607. Server &target() { return target_; }
  25608. int proxy_port() const { return proxy_port_; }
  25609. int target_port() const { return target_port_; }
  25610. int proxy_hits() const { return proxy_hits_.load(); }
  25611. int target_hits() const { return target_hits_.load(); }
  25612. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25613. void reset_counters() {
  25614. proxy_hits_ = 0;
  25615. target_hits_ = 0;
  25616. last_had_proxy_authz_ = false;
  25617. }
  25618. private:
  25619. Server proxy_mock_;
  25620. Server target_;
  25621. std::thread proxy_thread_;
  25622. std::thread target_thread_;
  25623. int proxy_port_ = 0;
  25624. int target_port_ = 0;
  25625. std::atomic<int> proxy_hits_{0};
  25626. std::atomic<int> target_hits_{0};
  25627. std::atomic<bool> last_had_proxy_authz_{false};
  25628. };
  25629. inline std::unique_ptr<Client> make_client(const std::string &host,
  25630. ProxyAndTargetServers &s) {
  25631. auto cli = detail::make_unique<Client>(host, s.target_port());
  25632. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25633. cli->set_proxy("127.0.0.1", s.proxy_port());
  25634. return cli;
  25635. }
  25636. } // namespace no_proxy_test
  25637. using no_proxy_test::make_client;
  25638. using no_proxy_test::ProxyAndTargetServers;
  25639. // A stream request carries the credentials a buffered request does
  25640. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25641. no_proxy_test::ScopedServer origin;
  25642. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25643. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25644. });
  25645. origin.listen();
  25646. Client cli("127.0.0.1", origin.port());
  25647. cli.set_basic_auth("user", "pass");
  25648. auto handle = cli.open_stream("GET", "/x");
  25649. ASSERT_TRUE(handle.is_valid());
  25650. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25651. Client bearer("127.0.0.1", origin.port());
  25652. bearer.set_bearer_token_auth("tok");
  25653. auto handle2 = bearer.open_stream("GET", "/x");
  25654. ASSERT_TRUE(handle2.is_valid());
  25655. EXPECT_EQ("Bearer tok", read_all(handle2));
  25656. }
  25657. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25658. // takes its own credentials, as for a buffered request
  25659. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25660. std::string target, authz, proxy_authz;
  25661. no_proxy_test::ScopedServer proxy;
  25662. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25663. target = req.target;
  25664. authz = req.get_header_value("Authorization");
  25665. proxy_authz = req.get_header_value("Proxy-Authorization");
  25666. res.set_content("ok", "text/plain");
  25667. });
  25668. proxy.listen();
  25669. Client cli("origin.example", 8080);
  25670. cli.set_proxy("127.0.0.1", proxy.port());
  25671. cli.set_proxy_basic_auth("puser", "ppass");
  25672. cli.set_basic_auth("user", "pass");
  25673. auto handle = cli.open_stream("GET", "/x");
  25674. ASSERT_TRUE(handle.is_valid());
  25675. EXPECT_EQ("ok", read_all(handle));
  25676. EXPECT_EQ("http://origin.example:8080/x", target);
  25677. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25678. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25679. }
  25680. TEST(NoProxyTest, ExactHostnameBypasses) {
  25681. ProxyAndTargetServers s;
  25682. auto cli = make_client("example.com", s);
  25683. cli->set_no_proxy({"example.com"});
  25684. auto res = cli->Get("/");
  25685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25686. EXPECT_EQ(0, s.proxy_hits());
  25687. EXPECT_EQ(1, s.target_hits());
  25688. }
  25689. TEST(NoProxyTest, SubdomainBypasses) {
  25690. ProxyAndTargetServers s;
  25691. auto cli = make_client("foo.example.com", s);
  25692. cli->set_no_proxy({"example.com"});
  25693. auto res = cli->Get("/");
  25694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25695. EXPECT_EQ(0, s.proxy_hits());
  25696. EXPECT_EQ(1, s.target_hits());
  25697. }
  25698. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25699. // Regression guard: "evilexample.com" must not be considered a subdomain
  25700. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25701. // check would let traffic bypass the proxy and leak credentials direct
  25702. // to the attacker host.
  25703. ProxyAndTargetServers s;
  25704. auto cli = make_client("evilexample.com", s);
  25705. cli->set_no_proxy({"example.com"});
  25706. auto res = cli->Get("/");
  25707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25708. EXPECT_GE(s.proxy_hits(), 1);
  25709. EXPECT_EQ(0, s.target_hits());
  25710. }
  25711. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25712. ProxyAndTargetServers s;
  25713. auto cli = make_client("example.com.evil.com", s);
  25714. cli->set_no_proxy({"example.com"});
  25715. auto res = cli->Get("/");
  25716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25717. EXPECT_GE(s.proxy_hits(), 1);
  25718. EXPECT_EQ(0, s.target_hits());
  25719. }
  25720. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25721. ProxyAndTargetServers s;
  25722. auto cli = make_client("example.com", s);
  25723. cli->set_no_proxy({".example.com"});
  25724. auto res = cli->Get("/");
  25725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25726. EXPECT_EQ(0, s.proxy_hits());
  25727. EXPECT_EQ(1, s.target_hits());
  25728. }
  25729. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25730. ProxyAndTargetServers s;
  25731. auto cli = make_client("Example.COM", s);
  25732. cli->set_no_proxy({"EXAMPLE.com"});
  25733. auto res = cli->Get("/");
  25734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25735. EXPECT_EQ(0, s.proxy_hits());
  25736. EXPECT_EQ(1, s.target_hits());
  25737. }
  25738. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25739. ProxyAndTargetServers s;
  25740. auto cli = make_client("example.com.", s);
  25741. cli->set_no_proxy({"example.com"});
  25742. auto res = cli->Get("/");
  25743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25744. EXPECT_EQ(0, s.proxy_hits());
  25745. EXPECT_EQ(1, s.target_hits());
  25746. }
  25747. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25748. // Trailing dots must be normalized on BOTH sides — host and entry.
  25749. // An implementation that only strips the host-side trailing dot would
  25750. // fail to match host "example.com" against entry "example.com." because
  25751. // a literal substring search would compare 11 chars against 12.
  25752. ProxyAndTargetServers s;
  25753. auto cli = make_client("example.com", s);
  25754. cli->set_no_proxy({"example.com."});
  25755. auto res = cli->Get("/");
  25756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25757. EXPECT_EQ(0, s.proxy_hits());
  25758. EXPECT_EQ(1, s.target_hits());
  25759. }
  25760. TEST(NoProxyTest, WildcardBypassesEverything) {
  25761. ProxyAndTargetServers s;
  25762. auto cli = make_client("anything.invalid.test", s);
  25763. cli->set_no_proxy({"*"});
  25764. auto res = cli->Get("/");
  25765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25766. EXPECT_EQ(0, s.proxy_hits());
  25767. EXPECT_EQ(1, s.target_hits());
  25768. }
  25769. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25770. ProxyAndTargetServers s;
  25771. Client cli("127.0.0.1", s.target_port());
  25772. cli.set_proxy("127.0.0.1", s.proxy_port());
  25773. cli.set_no_proxy({"127.0.0.1"});
  25774. auto res = cli.Get("/");
  25775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25776. EXPECT_EQ(0, s.proxy_hits());
  25777. EXPECT_EQ(1, s.target_hits());
  25778. }
  25779. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25780. ProxyAndTargetServers s;
  25781. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25782. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25783. cli.set_proxy("127.0.0.1", s.proxy_port());
  25784. cli.set_no_proxy({"::1"});
  25785. auto res = cli.Get("/");
  25786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25787. EXPECT_EQ(0, s.proxy_hits());
  25788. EXPECT_EQ(1, s.target_hits());
  25789. }
  25790. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25791. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25792. // must still be recognized as IPv6 for CIDR matching. Implementations
  25793. // that detect IPv6 only when the host begins with '[' would parse the
  25794. // host as a hostname and miss the match.
  25795. ProxyAndTargetServers s;
  25796. Client cli("fe80::1", s.target_port());
  25797. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25798. cli.set_proxy("127.0.0.1", s.proxy_port());
  25799. cli.set_no_proxy({"fe80::/10"});
  25800. auto res = cli.Get("/");
  25801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25802. EXPECT_EQ(0, s.proxy_hits());
  25803. EXPECT_EQ(1, s.target_hits());
  25804. }
  25805. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25806. ProxyAndTargetServers s;
  25807. Client cli("::1", s.target_port());
  25808. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25809. cli.set_proxy("127.0.0.1", s.proxy_port());
  25810. cli.set_no_proxy({"[::1]"});
  25811. auto res = cli.Get("/");
  25812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25813. EXPECT_EQ(0, s.proxy_hits());
  25814. EXPECT_EQ(1, s.target_hits());
  25815. }
  25816. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25817. ProxyAndTargetServers s;
  25818. Client cli("fe80::1", s.target_port());
  25819. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25820. cli.set_proxy("127.0.0.1", s.proxy_port());
  25821. cli.set_no_proxy({"[fe80::]/10"});
  25822. auto res = cli.Get("/");
  25823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25824. EXPECT_EQ(0, s.proxy_hits());
  25825. EXPECT_EQ(1, s.target_hits());
  25826. }
  25827. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25828. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25829. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25830. // tricks via address-family conversion.
  25831. ProxyAndTargetServers s;
  25832. Client cli("::ffff:127.0.0.1", s.target_port());
  25833. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25834. cli.set_proxy("127.0.0.1", s.proxy_port());
  25835. cli.set_no_proxy({"127.0.0.1"});
  25836. auto res = cli.Get("/");
  25837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25838. EXPECT_GE(s.proxy_hits(), 1);
  25839. EXPECT_EQ(0, s.target_hits());
  25840. }
  25841. TEST(NoProxyTest, IPv4CidrMatch) {
  25842. ProxyAndTargetServers s;
  25843. Client cli("127.0.0.1", s.target_port());
  25844. cli.set_proxy("127.0.0.1", s.proxy_port());
  25845. cli.set_no_proxy({"127.0.0.0/8"});
  25846. auto res = cli.Get("/");
  25847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25848. EXPECT_EQ(0, s.proxy_hits());
  25849. EXPECT_EQ(1, s.target_hits());
  25850. }
  25851. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25852. ProxyAndTargetServers s;
  25853. Client cli("127.0.0.1", s.target_port());
  25854. cli.set_proxy("127.0.0.1", s.proxy_port());
  25855. cli.set_no_proxy({"10.0.0.0/8"});
  25856. auto res = cli.Get("/");
  25857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25858. EXPECT_GE(s.proxy_hits(), 1);
  25859. EXPECT_EQ(0, s.target_hits());
  25860. }
  25861. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25862. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25863. // IPv4 target matches.
  25864. ProxyAndTargetServers s;
  25865. Client cli("127.0.0.1", s.target_port());
  25866. cli.set_proxy("127.0.0.1", s.proxy_port());
  25867. cli.set_no_proxy({"0.0.0.0/0"});
  25868. auto res = cli.Get("/");
  25869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25870. EXPECT_EQ(0, s.proxy_hits());
  25871. EXPECT_EQ(1, s.target_hits());
  25872. }
  25873. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25874. ProxyAndTargetServers s;
  25875. Client cli("127.0.0.1", s.target_port());
  25876. cli.set_proxy("127.0.0.1", s.proxy_port());
  25877. cli.set_no_proxy({"127.0.0.1"});
  25878. auto res = cli.Get("/");
  25879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25880. EXPECT_EQ(0, s.proxy_hits());
  25881. EXPECT_EQ(1, s.target_hits());
  25882. }
  25883. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25884. ProxyAndTargetServers s;
  25885. Client cli("127.0.0.1", s.target_port());
  25886. cli.set_proxy("127.0.0.1", s.proxy_port());
  25887. cli.set_no_proxy({"127.0.0.0/33"});
  25888. auto res = cli.Get("/");
  25889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25890. EXPECT_GE(s.proxy_hits(), 1);
  25891. EXPECT_EQ(0, s.target_hits());
  25892. }
  25893. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25894. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25895. ProxyAndTargetServers s;
  25896. Client cli("127.0.0.1", s.target_port());
  25897. cli.set_proxy("127.0.0.1", s.proxy_port());
  25898. cli.set_no_proxy({"127.0.0.1/"});
  25899. auto res = cli.Get("/");
  25900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25901. EXPECT_GE(s.proxy_hits(), 1);
  25902. EXPECT_EQ(0, s.target_hits());
  25903. }
  25904. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25905. ProxyAndTargetServers s;
  25906. auto cli = make_client("internal.corp", s);
  25907. cli->set_proxy_basic_auth("u", "p");
  25908. cli->set_no_proxy({"internal.corp"});
  25909. auto res = cli->Get("/");
  25910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25911. EXPECT_EQ(1, s.target_hits());
  25912. EXPECT_EQ(0, s.proxy_hits());
  25913. EXPECT_FALSE(s.last_had_proxy_authz())
  25914. << "Proxy-Authorization must not be sent direct to the target";
  25915. }
  25916. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25917. ProxyAndTargetServers s;
  25918. auto cli = make_client("public.example", s);
  25919. cli->set_proxy_basic_auth("u", "p");
  25920. cli->set_no_proxy({"internal.corp"}); // does not match
  25921. auto res = cli->Get("/");
  25922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25923. EXPECT_GE(s.proxy_hits(), 1);
  25924. EXPECT_TRUE(s.last_had_proxy_authz());
  25925. }
  25926. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25927. std::atomic<int> hits{0};
  25928. std::atomic<int> hits_with_authz{0};
  25929. no_proxy_test::ScopedServer proxy_mock;
  25930. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25931. hits++;
  25932. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25933. if (req.target.find("/redir") != std::string::npos) {
  25934. res.set_redirect("http://other.example/landed");
  25935. } else {
  25936. res.set_content("via-proxy", "text/plain");
  25937. }
  25938. });
  25939. proxy_mock.listen();
  25940. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25941. hits = 0;
  25942. hits_with_authz = 0;
  25943. Client cli("public.example", 80);
  25944. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25945. cli.set_proxy_basic_auth(c.first, c.second);
  25946. cli.set_follow_location(true);
  25947. // The redirect to another host goes through the proxy as well
  25948. auto res = cli.Get("/redir");
  25949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25950. EXPECT_EQ(2, hits.load());
  25951. EXPECT_EQ(2, hits_with_authz.load());
  25952. }
  25953. }
  25954. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25955. ProxyAndTargetServers s;
  25956. auto cli = make_client("anything.test", s);
  25957. auto res = cli->Get("/");
  25958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25959. EXPECT_GE(s.proxy_hits(), 1);
  25960. EXPECT_EQ(0, s.target_hits());
  25961. }
  25962. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25963. ProxyAndTargetServers s;
  25964. auto cli = make_client("example.com", s);
  25965. cli->set_no_proxy({"example.com:8080"});
  25966. auto res = cli->Get("/");
  25967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25968. EXPECT_GE(s.proxy_hits(), 1);
  25969. EXPECT_EQ(0, s.target_hits());
  25970. }
  25971. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25972. ProxyAndTargetServers s;
  25973. auto cli = make_client("anything.test", s);
  25974. cli->set_no_proxy({"", " ", "\t"});
  25975. auto res = cli->Get("/");
  25976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25977. EXPECT_GE(s.proxy_hits(), 1);
  25978. EXPECT_EQ(0, s.target_hits());
  25979. }
  25980. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25981. // An entry with leading/trailing whitespace must still match — env-style
  25982. // values are commonly pasted with stray spaces and an implementation
  25983. // that feeds the raw token directly to inet_pton would fail to match
  25984. // valid CIDRs because of the spaces.
  25985. ProxyAndTargetServers s;
  25986. Client cli("127.0.0.1", s.target_port());
  25987. cli.set_proxy("127.0.0.1", s.proxy_port());
  25988. cli.set_no_proxy({" 127.0.0.0/8 "});
  25989. auto res = cli.Get("/");
  25990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25991. EXPECT_EQ(0, s.proxy_hits());
  25992. EXPECT_EQ(1, s.target_hits());
  25993. }
  25994. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25995. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25996. // go direct and must NOT carry Proxy-Authorization.
  25997. std::atomic<int> proxy_hits{0};
  25998. std::atomic<int> target_hits{0};
  25999. std::atomic<bool> target_saw_authz{false};
  26000. no_proxy_test::ScopedServer proxy_mock, target;
  26001. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26002. proxy_hits++;
  26003. res.status = 302;
  26004. res.set_header("Location", "http://127.0.0.1:" +
  26005. std::to_string(target.port()) + "/landed");
  26006. });
  26007. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26008. target_hits++;
  26009. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26010. res.set_content("direct", "text/plain");
  26011. });
  26012. proxy_mock.listen();
  26013. target.listen();
  26014. Client cli("public.example", target.port());
  26015. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26016. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26017. cli.set_proxy_basic_auth("u", "p");
  26018. cli.set_no_proxy({"127.0.0.1"});
  26019. cli.set_follow_location(true);
  26020. auto res = cli.Get("/redir");
  26021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26022. EXPECT_GE(proxy_hits.load(), 1);
  26023. EXPECT_GE(target_hits.load(), 1);
  26024. EXPECT_FALSE(target_saw_authz.load());
  26025. }
  26026. #ifdef CPPHTTPLIB_SSL_ENABLED
  26027. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26028. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26029. // proxy creds would be sent to the (possibly hostile) origin.
  26030. std::atomic<int> target_hits{0};
  26031. std::atomic<bool> target_saw_proxy_authz{false};
  26032. no_proxy_test::ScopedServer target;
  26033. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26034. target_hits++;
  26035. if (req.has_header("Proxy-Authorization")) {
  26036. target_saw_proxy_authz = true;
  26037. }
  26038. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26039. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26040. "nonce=\"abc\", algorithm=MD5");
  26041. });
  26042. target.listen();
  26043. // The proxy address is set to the target's port: the bypass MUST kick in;
  26044. // if it doesn't, the test still routes "via proxy" to the same server and
  26045. // the Proxy-Authorization assertion below catches the leak.
  26046. Client cli("evil.example", target.port());
  26047. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26048. cli.set_proxy("127.0.0.1", target.port());
  26049. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26050. cli.set_no_proxy({"evil.example"});
  26051. auto res = cli.Get("/x");
  26052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26053. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26054. EXPECT_EQ(1, target_hits.load());
  26055. EXPECT_FALSE(target_saw_proxy_authz.load());
  26056. }
  26057. #endif
  26058. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26059. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26060. std::atomic<int> proxy_hits{0};
  26061. std::atomic<int> bypass_hits{0};
  26062. std::atomic<bool> proxy_saw_c_url{false};
  26063. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26064. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26065. proxy_hits++;
  26066. if (req.path.find("/start") != std::string::npos) {
  26067. res.status = 302;
  26068. res.set_header("Location", "http://127.0.0.1:" +
  26069. std::to_string(bypass_server.port()) +
  26070. "/middle");
  26071. return;
  26072. }
  26073. if (req.path.find("/end") != std::string::npos) {
  26074. proxy_saw_c_url = true;
  26075. res.set_content("c-via-proxy", "text/plain");
  26076. return;
  26077. }
  26078. res.set_content("unexpected", "text/plain");
  26079. });
  26080. // public.example's "advertised" port is arbitrary (the request never lands
  26081. // there — it goes through the proxy), but use a dynamic value to stay
  26082. // friendly with sharded parallel runs.
  26083. int public_port = bypass_server.port();
  26084. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26085. bypass_hits++;
  26086. res.status = 302;
  26087. res.set_header("Location", "http://public.example:" +
  26088. std::to_string(public_port) + "/end");
  26089. });
  26090. proxy_mock.listen();
  26091. bypass_server.listen();
  26092. Client cli("public.example", public_port);
  26093. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26094. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26095. cli.set_no_proxy({"127.0.0.1"});
  26096. cli.set_follow_location(true);
  26097. auto res = cli.Get("/start");
  26098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26099. EXPECT_EQ(StatusCode::OK_200, res->status);
  26100. EXPECT_EQ("c-via-proxy", res->body);
  26101. EXPECT_GE(proxy_hits.load(), 2);
  26102. EXPECT_GE(bypass_hits.load(), 1);
  26103. EXPECT_TRUE(proxy_saw_c_url.load());
  26104. }
  26105. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26106. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26107. // request reconnects to the correct endpoint.
  26108. std::atomic<int> proxy_hits{0};
  26109. std::atomic<int> target_hits{0};
  26110. no_proxy_test::ScopedServer proxy_mock, target;
  26111. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26112. proxy_hits++;
  26113. res.set_content("via-proxy", "text/plain");
  26114. });
  26115. target.svr().Get(".*", [&](const Request &, Response &res) {
  26116. target_hits++;
  26117. res.set_content("direct", "text/plain");
  26118. });
  26119. proxy_mock.listen();
  26120. target.listen();
  26121. Client cli("public.example", target.port());
  26122. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26123. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26124. cli.set_keep_alive(true);
  26125. auto res1 = cli.Get("/a");
  26126. ASSERT_TRUE(res1);
  26127. EXPECT_EQ("via-proxy", res1->body);
  26128. EXPECT_EQ(1, proxy_hits.load());
  26129. EXPECT_EQ(0, target_hits.load());
  26130. cli.set_no_proxy({"public.example"});
  26131. auto res2 = cli.Get("/b");
  26132. ASSERT_TRUE(res2);
  26133. EXPECT_EQ("direct", res2->body);
  26134. EXPECT_EQ(1, proxy_hits.load());
  26135. EXPECT_EQ(1, target_hits.load());
  26136. }
  26137. // Forward declarations (see the base64_encode note).
  26138. namespace httplib {
  26139. namespace detail {
  26140. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26141. int shutdown_socket(socket_t sock) noexcept;
  26142. } // namespace detail
  26143. } // namespace httplib
  26144. namespace proxy_tunnel_test {
  26145. const char *const kTunnelEstablished =
  26146. "HTTP/1.1 200 Connection established\r\n\r\n";
  26147. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26148. using ConnectReply = std::function<std::string(const std::string &head)>;
  26149. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26150. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26151. class ScopedConnectProxy {
  26152. public:
  26153. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26154. : forward_port_(forward_port), reply_(std::move(reply)) {
  26155. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26156. if (listen_sock_ == INVALID_SOCKET) { return; }
  26157. auto a = loopback(0);
  26158. auto addr = reinterpret_cast<sockaddr *>(&a);
  26159. socklen_t alen = sizeof(a);
  26160. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26161. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26162. ::listen(listen_sock_, 4) != 0) {
  26163. return;
  26164. }
  26165. port_ = ntohs(a.sin_port);
  26166. th_ = std::thread([this] { run(); });
  26167. }
  26168. ~ScopedConnectProxy() {
  26169. if (th_.joinable()) {
  26170. stop_ = true;
  26171. auto wake = connect_to(port_);
  26172. th_.join();
  26173. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26174. }
  26175. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26176. }
  26177. int port() const { return port_; }
  26178. int connect_hits() const { return connect_hits_.load(); }
  26179. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26180. std::string connect_request() const {
  26181. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26182. return connect_request_;
  26183. }
  26184. private:
  26185. static sockaddr_in loopback(int port) {
  26186. sockaddr_in a{};
  26187. a.sin_family = AF_INET;
  26188. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26189. a.sin_port = htons(static_cast<unsigned short>(port));
  26190. return a;
  26191. }
  26192. static socket_t connect_to(int port) {
  26193. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26194. if (sock == INVALID_SOCKET) { return sock; }
  26195. auto a = loopback(port);
  26196. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26197. detail::close_socket(sock);
  26198. return INVALID_SOCKET;
  26199. }
  26200. return sock;
  26201. }
  26202. static bool send_all(socket_t sock, const char *data, size_t size) {
  26203. while (size > 0) {
  26204. auto n = detail::send_socket(sock, data, size, 0);
  26205. if (n <= 0) { return false; }
  26206. data += n;
  26207. size -= static_cast<size_t>(n);
  26208. }
  26209. return true;
  26210. }
  26211. void run() {
  26212. for (;;) {
  26213. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26214. if (stop_) {
  26215. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26216. return;
  26217. }
  26218. if (client == INVALID_SOCKET) { continue; }
  26219. serve(client);
  26220. detail::close_socket(client);
  26221. }
  26222. }
  26223. void serve(socket_t client) {
  26224. std::string head;
  26225. char buf[2048];
  26226. while (head.find("\r\n\r\n") == std::string::npos) {
  26227. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26228. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26229. if (n <= 0) { return; }
  26230. head.append(buf, static_cast<size_t>(n));
  26231. }
  26232. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26233. connect_hits_++;
  26234. {
  26235. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26236. connect_request_ = head;
  26237. }
  26238. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26239. if (!send_all(client, res.data(), res.size()) ||
  26240. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26241. return;
  26242. }
  26243. auto origin = connect_to(forward_port_);
  26244. if (origin == INVALID_SOCKET) { return; }
  26245. // When either side stops, shut both down so the other pump returns too.
  26246. auto pump = [&](socket_t from, socket_t to) {
  26247. char b[8192];
  26248. for (;;) {
  26249. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26250. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26251. }
  26252. detail::shutdown_socket(client);
  26253. detail::shutdown_socket(origin);
  26254. };
  26255. std::thread up([&] { pump(client, origin); });
  26256. pump(origin, client);
  26257. up.join();
  26258. detail::close_socket(origin);
  26259. }
  26260. int forward_port_;
  26261. ConnectReply reply_;
  26262. socket_t listen_sock_ = INVALID_SOCKET;
  26263. int port_ = 0;
  26264. std::thread th_;
  26265. std::atomic<bool> stop_{false};
  26266. std::atomic<int> connect_hits_{0};
  26267. mutable std::mutex connect_request_mutex_;
  26268. std::string connect_request_;
  26269. };
  26270. } // namespace proxy_tunnel_test
  26271. #ifdef CPPHTTPLIB_SSL_ENABLED
  26272. namespace proxy_tunnel_test {
  26273. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26274. class ScopedSSLServer {
  26275. public:
  26276. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26277. port_ = svr_.bind_to_any_port("127.0.0.1");
  26278. }
  26279. ~ScopedSSLServer() {
  26280. svr_.stop();
  26281. if (th_.joinable()) { th_.join(); }
  26282. }
  26283. SSLServer &svr() { return svr_; }
  26284. int port() const { return port_; }
  26285. void listen() {
  26286. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26287. svr_.wait_until_ready();
  26288. }
  26289. private:
  26290. SSLServer svr_;
  26291. std::thread th_;
  26292. int port_ = 0;
  26293. };
  26294. // Sends one request through the CONNECT proxy to the TLS origin with a
  26295. // credential configured for each hop, and checks that each credential reaches
  26296. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26297. // origin's (every header in origin_headers) on the tunnelled request.
  26298. void CredentialsStayWithTheirHop(
  26299. const std::function<void(SSLClient &)> &set_credentials,
  26300. const std::string &scheme,
  26301. const std::vector<std::string> &origin_headers = {"Authorization"},
  26302. bool stream = false) {
  26303. std::atomic<int> origin_hits{0};
  26304. std::atomic<bool> origin_saw_proxy_authz{false};
  26305. std::atomic<bool> origin_saw_headers{false};
  26306. ScopedSSLServer origin;
  26307. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26308. origin_hits++;
  26309. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26310. origin_saw_headers =
  26311. std::all_of(origin_headers.begin(), origin_headers.end(),
  26312. [&](const std::string &h) { return req.has_header(h); });
  26313. res.set_content("ok", "text/plain");
  26314. });
  26315. origin.listen();
  26316. ScopedConnectProxy proxy(origin.port());
  26317. ASSERT_NE(0, proxy.port());
  26318. // Pinned to 127.0.0.1 for the same reason as the test below.
  26319. SSLClient cli("127.0.0.1", origin.port());
  26320. cli.enable_server_certificate_verification(false);
  26321. cli.set_proxy("127.0.0.1", proxy.port());
  26322. set_credentials(cli);
  26323. if (stream) {
  26324. auto handle = cli.open_stream("GET", "/x");
  26325. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26326. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26327. } else {
  26328. auto res = cli.Get("/x");
  26329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26330. EXPECT_EQ(StatusCode::OK_200, res->status);
  26331. }
  26332. EXPECT_EQ(1, origin_hits.load());
  26333. EXPECT_EQ(1, proxy.connect_hits());
  26334. EXPECT_TRUE(origin_saw_headers.load());
  26335. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26336. << "Proxy-Authorization must not be sent inside the tunnel";
  26337. auto connect_req = proxy.connect_request();
  26338. EXPECT_NE(std::string::npos,
  26339. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26340. for (const auto &h : origin_headers) {
  26341. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26342. << h << " must not be sent to the proxy on CONNECT";
  26343. }
  26344. }
  26345. } // namespace proxy_tunnel_test
  26346. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26347. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26348. [](SSLClient &cli) {
  26349. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26350. cli.set_basic_auth("origin-user", "origin-pass");
  26351. },
  26352. "Basic");
  26353. }
  26354. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26355. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26356. [](SSLClient &cli) {
  26357. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26358. cli.set_basic_auth("origin-user", "origin-pass");
  26359. },
  26360. "Basic", {"Authorization"}, true);
  26361. }
  26362. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26363. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26364. [](SSLClient &cli) {
  26365. cli.set_proxy_bearer_token_auth("proxy-token");
  26366. cli.set_bearer_token_auth("origin-token");
  26367. },
  26368. "Bearer");
  26369. }
  26370. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26371. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26372. [](SSLClient &cli) {
  26373. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26374. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26375. {"Cookie", "sid=origin-session"},
  26376. {"X-Api-Key", "origin-key"}});
  26377. },
  26378. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26379. }
  26380. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26381. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26382. // retry; otherwise proxy creds would be sent to the origin.
  26383. std::atomic<int> origin_hits{0};
  26384. std::atomic<bool> origin_saw_proxy_authz{false};
  26385. proxy_tunnel_test::ScopedSSLServer origin;
  26386. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26387. origin_hits++;
  26388. if (req.has_header("Proxy-Authorization")) {
  26389. origin_saw_proxy_authz = true;
  26390. }
  26391. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26392. res.set_header("Proxy-Authenticate",
  26393. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26394. "algorithm=MD5");
  26395. });
  26396. origin.listen();
  26397. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26398. ASSERT_NE(0, proxy.port());
  26399. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26400. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26401. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26402. // and answer with its own status, making this test flaky.
  26403. SSLClient cli("127.0.0.1", origin.port());
  26404. cli.enable_server_certificate_verification(false);
  26405. cli.set_proxy("127.0.0.1", proxy.port());
  26406. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26407. auto res = cli.Get("/x");
  26408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26409. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26410. EXPECT_EQ(1, origin_hits.load());
  26411. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26412. EXPECT_EQ(1, proxy.connect_hits());
  26413. }
  26414. #endif
  26415. namespace proxy_tunnel_test {
  26416. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26417. // anything else gets a 407 with `challenge`.
  26418. ConnectReply require_proxy_auth(const std::string &expected,
  26419. const std::string &challenge) {
  26420. return [=](const std::string &head) -> std::string {
  26421. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26422. std::string::npos) {
  26423. return kTunnelEstablished;
  26424. }
  26425. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26426. "Proxy-Authenticate: " +
  26427. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26428. };
  26429. }
  26430. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26431. // request, then echoes.
  26432. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26433. ws.send(
  26434. "authorization:" + req.get_header_value("Authorization") +
  26435. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26436. std::string msg;
  26437. while (ws.read(msg)) {
  26438. ws.send(msg);
  26439. }
  26440. }
  26441. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26442. class ScopedWebSocketOrigin {
  26443. public:
  26444. ScopedWebSocketOrigin() {
  26445. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26446. server_.listen();
  26447. }
  26448. int port() const { return server_.port(); }
  26449. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26450. std::string url() const {
  26451. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26452. }
  26453. private:
  26454. no_proxy_test::ScopedServer server_;
  26455. };
  26456. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26457. // passed as a constructor header, and checks that each reaches only its hop.
  26458. void WebSocketCredentialsStayWithTheirHop(
  26459. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26460. const std::string &proxy_authz, const std::string &origin_authz) {
  26461. ScopedWebSocketOrigin origin;
  26462. ScopedConnectProxy proxy(
  26463. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26464. ASSERT_NE(0, proxy.port());
  26465. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26466. client.set_proxy("127.0.0.1", proxy.port());
  26467. set_proxy_credentials(client);
  26468. auto res = client.connect();
  26469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26470. std::string msg;
  26471. ASSERT_TRUE(client.read(msg));
  26472. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26473. client.close();
  26474. EXPECT_EQ(1, proxy.connect_hits());
  26475. EXPECT_EQ(std::string::npos,
  26476. proxy.connect_request().find("\r\nAuthorization: "))
  26477. << "origin credentials must not be sent to the proxy";
  26478. }
  26479. } // namespace proxy_tunnel_test
  26480. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26481. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26482. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26483. ASSERT_NE(0, proxy.port());
  26484. ws::WebSocketClient client(origin.url());
  26485. client.set_proxy("127.0.0.1", proxy.port());
  26486. auto res = client.connect();
  26487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26488. std::string msg;
  26489. ASSERT_TRUE(client.read(msg));
  26490. ASSERT_TRUE(client.send("hello"));
  26491. ASSERT_TRUE(client.read(msg));
  26492. EXPECT_EQ("hello", msg);
  26493. client.close();
  26494. EXPECT_EQ(1, proxy.connect_hits());
  26495. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26496. auto connect_req = proxy.connect_request();
  26497. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26498. EXPECT_NE(std::string::npos,
  26499. connect_req.find("\r\nHost: " + target + "\r\n"));
  26500. }
  26501. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26502. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26503. [](ws::WebSocketClient &cli) {
  26504. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26505. },
  26506. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26507. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26508. }
  26509. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26510. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26511. [](ws::WebSocketClient &cli) {
  26512. cli.set_proxy_bearer_token_auth("proxy-token");
  26513. },
  26514. "Bearer proxy-token", "Bearer origin-token");
  26515. }
  26516. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26517. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26518. proxy_tunnel_test::ScopedConnectProxy proxy(
  26519. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26520. "Basic " + detail::base64_encode("proxy-user:"),
  26521. "Basic realm=\"proxy\""));
  26522. ASSERT_NE(0, proxy.port());
  26523. ws::WebSocketClient client(origin.url());
  26524. client.set_proxy("127.0.0.1", proxy.port());
  26525. client.set_proxy_basic_auth("proxy-user", "");
  26526. auto res = client.connect();
  26527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26528. client.close();
  26529. EXPECT_EQ(1, proxy.connect_hits());
  26530. }
  26531. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26532. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26533. proxy_tunnel_test::ScopedConnectProxy proxy(
  26534. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26535. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26536. ASSERT_NE(0, proxy.port());
  26537. ws::WebSocketClient client(origin.url());
  26538. client.set_proxy("127.0.0.1", proxy.port());
  26539. auto res = client.connect();
  26540. EXPECT_FALSE(res);
  26541. EXPECT_EQ(Error::ProxyConnection, res.error());
  26542. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26543. EXPECT_EQ("Basic realm=\"proxy\"",
  26544. res.get_header_value("Proxy-Authenticate"));
  26545. EXPECT_FALSE(client.is_open());
  26546. }
  26547. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26548. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26549. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26550. ASSERT_NE(0, proxy.port());
  26551. ws::WebSocketClient client(origin.url());
  26552. client.set_proxy("127.0.0.1", proxy.port());
  26553. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26554. client.set_no_proxy({"127.0.0.1"});
  26555. auto res = client.connect();
  26556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26557. std::string msg;
  26558. ASSERT_TRUE(client.read(msg));
  26559. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26560. << "proxy credentials must not reach a bypassed origin";
  26561. client.close();
  26562. EXPECT_EQ(0, proxy.connect_hits());
  26563. }
  26564. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26565. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26566. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26567. ASSERT_NE(0, proxy.port());
  26568. ws::WebSocketClient client(origin.url());
  26569. client.set_proxy("127.0.0.1", proxy.port());
  26570. ASSERT_TRUE(client.connect());
  26571. ASSERT_TRUE(client.connect());
  26572. client.close();
  26573. EXPECT_EQ(2, proxy.connect_hits());
  26574. }
  26575. #ifdef CPPHTTPLIB_SSL_ENABLED
  26576. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26577. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26578. proxy_tunnel_test::ScopedConnectProxy proxy(
  26579. origin.port(), [](const std::string &head) -> std::string {
  26580. if (head.find(
  26581. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26582. std::string::npos) {
  26583. return proxy_tunnel_test::kTunnelEstablished;
  26584. }
  26585. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26586. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26587. "nonce=\"abc\", algorithm=MD5\r\n"
  26588. "Content-Length: 0\r\n\r\n";
  26589. });
  26590. ASSERT_NE(0, proxy.port());
  26591. ws::WebSocketClient client(origin.url());
  26592. client.set_proxy("127.0.0.1", proxy.port());
  26593. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26594. auto res = client.connect();
  26595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26596. std::string msg;
  26597. ASSERT_TRUE(client.read(msg));
  26598. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26599. client.close();
  26600. EXPECT_EQ(2, proxy.connect_hits());
  26601. }
  26602. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26603. proxy_tunnel_test::ScopedSSLServer origin;
  26604. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26605. origin.listen();
  26606. proxy_tunnel_test::ScopedConnectProxy proxy(
  26607. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26608. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26609. ASSERT_NE(0, proxy.port());
  26610. ws::WebSocketClient client(
  26611. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26612. client.enable_server_certificate_verification(false);
  26613. client.set_proxy("127.0.0.1", proxy.port());
  26614. client.set_proxy_bearer_token_auth("proxy-token");
  26615. auto res = client.connect();
  26616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26617. std::string msg;
  26618. ASSERT_TRUE(client.read(msg));
  26619. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26620. << "Proxy-Authorization must not be sent inside the tunnel";
  26621. client.close();
  26622. EXPECT_EQ(1, proxy.connect_hits());
  26623. }
  26624. #endif